首页 > 语言 > JavaScript > 正文

vue如何在自定义组件中使用v-model

2024-05-06 15:34:14
字体:
来源:转载
供稿:网友

v-model指令

所谓的“指令”其实就是扩展了HTML标签功能(属性)。

先来一个组件,不用vue-model,正常父子通信

<!-- parent --><template><div class="parent">  <p>我是父亲, 对儿子说: {{sthGiveChild}}</p>  <Child @returnBack="turnBack" :give="sthGiveChild"></Child></div></template><script>import Child from './Child.vue';export default {  data() {    return {      sthGiveChild: '给你100块'    };  },  components: {    Child  },  methods: {    turnBack(val) {      this.sthGiveChild = val;    }  }}</script>
<!-- child --><template><div class="child">  <p>我是儿子,父亲对我说: {{give}}</p>  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="returnBackFn">回应</a></div></template><script>export default {  props: {    give: String  },  methods: {    returnBackFn() {      this.$emit('returnBack', '还你200块');    }  }}</script>

点击回应后,父亲对儿子说的话变成了儿子的回应。儿子收到的信息也变了,实现通信。

改用v-model

<!-- parent --><template><div class="parent">  <p>我是父亲, 对儿子说: {{sthGiveChild}}</p>  <Child v-model="sthGiveChild"></Child></div></template><script>import Child from './Child.vue';export default {  data() {    return {      sthGiveChild: '给你100块'    };  },  components: {    Child  }}</script>
<!-- child --><template><div class="child">  <p>我是儿子,父亲对我说: {{give}}</p>  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="returnBackFn">回应</a></div></template><script>export default {  props: {    give: String  },  model: {    prop: 'give',    event: 'returnBack'  },  methods: {    returnBackFn() {      this.$emit('returnBack', '还你200块');    }  }}</script>

文案虽有不同,但是效果最终是一致的。

看看官方自定义组件的v-model

官方例子https://vuefe.cn/v2/api/#model

有这么一句话: 默认情况下,一个组件上的 v-model 会把 value 用作 prop 且把 input 用作 event。

尝试把上边子组件的例子改一下,也是跑的通的

<!-- child --><template><div class="child">  <p>我是儿子,父亲对我说: {{value}}</p>  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="returnBackFn">回应</a></div></template><script>export default {  props: {    value: String  },  methods: {    returnBackFn() {      this.$emit('input', '还你200块');    }  }}</script>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选