Vue-props和this.emit()

  • vue组件中的props:props允许vue组件获得vue实例中data域中的数据(得通过绑定)
  • this.$emit(),允许vue组件中的函数指向vue实例中的函数并执行(事件的声明得需要绑定)
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <todo>
            <todo-title slot="todo-title" :ctitle="title"></todo-title>
            <todo-items slot="todo-items" v-for="(item,index) in items" :citem="item" @remove="removeItem(index)"></todo-items>
        </todo>
    </div>

    <script>
        Vue.component("todo", {
            template:
                '
' + '' + '
    ' + '' + '
'
+ '
'
}); Vue.component("todo-title", { props: ['ctitle'], template: '
{{ctitle}}
'
}); Vue.component("todo-items", { props: ['citem'],//props 允许组件获得vue实例中的data中的数据,数据由vue实例到vue组件 template: '
  • {{citem}}
  • '
    , methods: { cremove: function (index) { //this.$emit()允许组件可以执行vue实例中的方法,方法由vue组件到vue实例 this.$emit("remove", index);//这里的remove对应上面的自定义的事件名,关联至vue实例中的removeItem方法 } } }); var vm = new Vue({ el: '#app', data: { title: '列表', items: ['吃饭', '睡觉'] }, methods: { removeItem: function(index) { this.items.splice(index); } } }); </script> </body> </html>

    你可能感兴趣的:(Vue)