【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


    

JQuery

<body>
    <h1>Todo Listh1>
    <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>