<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>演示分别使用 v-bind和v-model与子组件进行数据交互</title>
<script src="vue.js"></script>
</head>
<body>
<!--组件封装-->
<template id="vm">
<div>
<div>
<input v-model="ival" type="checkbox" />{{p1}}
</div>
</div>
</template>
<script>
Vue.component("vm-test1", {
template: '#vm',
props: {
//p1用于接收 父中的v-model的值
p1: { type: String, default: "" },
on: { type: String, default: "1" },
off: { type: String, default: "0" },
},
//model必须叫input的事件名给起一个别名,在这里叫update
model: {
prop: "p1", //p1用于接收 父中的v-model的值
event:"update1"
},
created: function () {
this.ival = this.p1 == this.on;
},
mounted: function () {
},
data: function () {
return {ival: ""};
},
watch: {
ival: function (newValue, oldValue) {
this.$emit("update1", this.ival ? this.on : this.off);
},
p1: function (newValue, oldValue) {
this.ival = this.p1 == this.on;
}
}
});
</script>
<!--使用示例-->
<div id="app">
使用组件示例 :
<vm-test1 :on="1" :off="0" v-model="text"> </vm-test1>
</div>
<script>
let test = new Vue({
el: "#app",
data: {
text: "1",
}
});
</script>
</body>
</html>
封装vue组件
最新推荐文章于 2023-12-24 08:00:00 发布