modal:单向绑定
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
.mask {
width: 100%;
height: 100%;
position: fixed;
background: rgba(0, 0, 0, .35);
top: 0;
left: 0
}
.dialog {
width: 400px;
height: 150px;
background: #fff;
position: fixed;
top: 50%;
left: 50%;
transform: translate3d(-50%, -50%, 0)
}
</style>
</head>
<body>
<div id="app">
<button @click="flag=true">click</button>
<mymodal :childflag="flag" @childthings="()=>flag=false"></mymodal>
</div>
<template id="dialog">
<div class="mask" v-show="childflag">
<div class="dialog">
<button @click="shutdown">关闭</button>
</div>
</div>
</template>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
let vm = new Vue({
el: "#app",
data: {
flag: false,
},
components: {
mymodal: {
props: ['childflag'],
template: "#dialog",
methods: {
shutdown() {
this.$emit('childthings')
}
}
},
}
})
</script>
modal:双向绑定
<head>
<meta charset="UTF-8">
<title>modal</title>
<style>
.mask {
width: 100%;
height: 100%;
position: fixed;
background: rgba(0, 0, 0, .35);
top: 0;
left: 0
}
.dialog {
width: 400px;
height: 150px;
background: #fff;
position: fixed;
top: 50%;
left: 50%;
transform: translate3d(-50%, -50%, 0)
}
</style>
</head>
<body>
<div id="app">
<modal :childflag="flag" @childthings="things"></modal>
<button @click="open">open</button>
</div>
<template id="dialog">
<div class="mask" v-show="mychildflag">
<div class="dialog">
<button @click="childclose">close</button>
</div>
</div>
</template>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
let vm = new Vue({
el: "#app",
data: {
msg: "maotai",
flag: false,
},
methods: {
open() {
this.flag = true;
},
things(val) {
this.flag = val;
}
},
components: {
modal: {
props: ['childflag'],
data() {
return {
mychildflag: this.childflag,
}
},
watch: {
childflag(val) {
this.mychildflag = val;
},
mychildflag(val) {
this.$emit('childthings', val)
}
},
methods: {
childclose() {
this.mychildflag = !this.mychildflag;
}
},
template: "#dialog"
}
}
})
</script>
双向绑定解释
<div id="app">
<switchbtn :result="result" @on-result-change="onResultChange"></switchbtn>
<input type="button" value="change" @click="change">
</div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
Vue.component("switchbtn", {
props: ["result"],
data: function () {
return {
myResult: this.result//①创建props属性result的副本--myResult
};
},
watch: {
result(val) {
this.myResult = val;//②监听外部对props属性result的变更,并同步到组件内的data属性myResult中
},
myResult(val) {
this.$emit("on-result-change", val);//③组件内对myResult变更后向外部发送事件通知
}
},
methods: {
change() {
this.myResult = !this.myResult;
}
},
template: "<div @click='change'>{{myResult?'开':'关'}}</div>"
});
let vm = new Vue({
el: "#app",
data: {
result: true
},
methods: {
change() {
this.result = !this.result;
},
onResultChange(val) {
this.result = val;//④外层调用组件方注册变更方法,将组件内的数据变更,同步到组件外的数据状态中
}
}
});
</script>