【JavaScript】Vue/React/JQuery代码对比 分别实现TodoList
Vue
<body> <div id="app"></div> <script> const Add = { props: ['size'], data() { return { value: '' } }, template: ` <div> <input v-model="value"/> <button @click="$emit('add', value)">Add ({{size}})</button> </div> ` } const List = { props: ['list'], template: ` <ul> <li v-for="(v, i) of list" :key="i">{{v}}</li> </ul> ` } const App = { components: { Add, List }, data: { list: [] }, computed: { size() { return this.list.length } }, methods: { add(value) { if (value != '') this.list.unshift(value) } }, template: ` <div> <h1>Todo List</h1> <Add :size="size" @add="add"></Add> <List :list="list"></List> </div> ` } new Vue(App).$mount('#app') </script> </body>
React
<body> <div id="app"></div> <script type="text/babel"> class Add extends React.Component { add = () => { this.props.add(this.input.value) } render() { return ( <div> <input ref={(input) => { this.input = input }} type="text" /> <button onClick={this.add}>Add ({this.props.size})</button> </div> ) } } class List extends React.Component { render() { const { list } = this.props return ( <ul> {list.map((v, k) => <li key={k}>{v}</li>)} </ul> ) } } class App extends React.Component { state = { list: [] } add = (value) => { if (value == '') return
const list = [...this.state.list] list.unshift(value) this.setState({ list }) } render() { return ( <div> <h1>Todo List</h1> <Add add={this.add} size={this.state.list.length} /> <List list={this.state.list} /> </div> ) } } ReactDOM.render(<App />, document.getElementById('app')) </script> </body>
JQuery
<body> <h1>Todo List</h1> <input type="text"> <button id="btn">Add (<span></span>)</button> <ul id="list"></ul> <script> (() => { const ul = $('#list') const btn = $('#btn') btn.find('span').text(ul.find('li').length) btn.click(function () { ul.prepend( `<li>${$(this).prev().val()}</li>` ) $(this).find('span').text(ul.find('li').length) }) })() </script> </body>