本人是一個後臺,,但是對於前端技術頗具興趣,所以vue以前研究過一段時間,也在項目當中使用過,不過不是前後端分離,並沒有使用到vue的精髓部分(template),只是使用其mvvm的開發方式,感覺還是很方便的,現在稍微看了下react,也被這語法深深吸引了,,所以寫了兩個todolist,大家感受一下:(以下代碼新建一個html,拷進去就可以運行了,有什麼不明白的,歡迎留言探討……)
<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- react -->
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
<!-- vue -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<style>
.fail{
color:red;
}
</style>
</head>
<body>
<div id="todo1"></div>
<div id="todo2">
<input type="text" v-model="value"><button style="width:50px; height:30px;" @click="addObj">新增</button>
<ul>
<li v-for="obj in arr">
{{ obj }}<span class="fail" @click="removeObj">×</span>
</li>
</ul>
</div>
</body>
<script type="text/babel">
/**** 基於es6模塊化的寫法 ****/
class Todo extends React.Component{
constructor(props){
super(props);
// props可接受組件傳入的屬性prop
alert('author: ' + props.author);
// 初始化state的值
this.state = {arr: [], id: 0};
// 事件函數綁定this, 在class中事件函數的this必須顯示的由自己來綁定,有三種方法,這是第一種
this.handleFailClick = this.handleFailClick.bind(this, '李四')
}
handleClick(event) {
let arr = this.state.arr;
let id = this.state.id;
// id是爲了生成的元素的key屬性,詳細看react文檔
arr.push({data: this.state.value, id: id++});
this.setState({arr: arr, id: id});
}
// 箭頭函數是第二種函數的this綁定方法
handleChange = (event) =>{
this.setState({value: event.target.value})
}
handleFailClick(name, event){
console.log(name)
console.log(this.state);
var liObj = event.target.parentNode;
var ulObj = liObj.parentNode;
ulObj.removeChild(liObj);
}
render(){
return(
<div>
<input type="text" onChange={this.handleChange}/><button onClick={this.handleClick.bind(this)} style={{ width:'50px', height:'23px',marginTop:'2px'}}>新增</button>
<ul>
{
this.state.arr.map((obj) => {
return(
<li key={ obj.id.toString() }>{ obj.data }<span className='fail' onClick={this.handleFailClick}>×</span></li>
)
})
}
</ul>
</div>
)
}
}
ReactDOM.render(<Todo author="sunh"/>, document.getElementById('todo1'))
</script>
<script>
/** 以下爲vue的實現 **/
var app = new Vue({
el: '#todo2',
data: {
arr: [],
value: null
},
methods: {
addObj : function(event){
console.log(event)
this.arr.push(this.value);
},
removeObj(event){
var target = event.target;
var liObj = target.parentNode;
var ulObj = liObj.parentNode;
ulObj.removeChild(liObj);
}
}
})
</script>
</html>