vue学习之自定义事件

通过自定义事件可以实现vue组件”子->父”的数据传递

由子组件$emit事件的名称,父组件监听这个名称的事件,事件名称的命名推荐使用 “kebab-case” 的形式。

下面代码中,子组件给父组件传递了一个弹框信息。

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>vue</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="vue.js"></script>
</head>

<body>
    <div id="app">
        <child-div @alert="notice" :msg="msg"></child-div>
    </div>
    <script>
        Vue.component('child-div', {
            template: '<div @click="childNotice">点我,父组件弹通知</div>',
            methods:{
                childNotice: function(){
                    this.$emit('alert', 'Hello Vue');
                }
            }
        });
        let app = new Vue({
            el: '#app',
            methods:{
                notice: function(msg){
                    alert(`来自子组件:${msg}`);
                }
            }
        });
    </script>

</body>

</html>

.sync 修饰符 (2.3.0+ 新增)

举个例子,在一个包含 title prop 的假设的组件中,我们可以用以下方法表达对其赋新值的意图:

this.$emit('update:title', newTitle)

然后父组件可以监听那个事件并根据需要更新一个本地的数据属性。例如:

<text-document
  v-bind:title="doc.title"
  v-on:update:title="doc.title = $event"
></text-document>

为了方便起见,我们为这种模式提供一个缩写,即 .sync 修饰符:

<text-document v-bind:title.sync="doc.title"></text-document>

当我们用一个对象同时设置多个 prop 的时候,也可以将这个 .sync 修饰符和 v-bind 配合使用:

<text-document v-bind.sync="doc"></text-document>

这样会把 doc 对象中的每一个属性 (如 title) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on 监听器。

猜你喜欢

转载自blog.csdn.net/summerpowerz/article/details/80724604