vue自定义组件实现v-model双向绑定
父级组件
<template> <div id="app"> <button @click="clickme">click me</button> <img alt="Vue logo" src="./assets/logo.png" /> <HelloWorld msg="Welcome to Your Vue.js App" v-model="show" /> </div> </template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { name: "App", data() { return { show: true }; }, components: { HelloWorld }, methods: { clickme() { this.show = !this.show; } } }; </script>
子组件
<template> <div class="hello" v-show="value"> <h1>{{ msg }}</h1> <button @click="clickme">click child</button> </div> </template> <script> export default { name: "HelloWorld", props: { msg: String, value: Boolean// 获取父级组件传递的value }, updated() {}, methods: { clickme() { const newval = !this.value; this.$emit("input", newval); //v-model实现的是v-bind:value 和v-on:input,这句更新父级组件的value } } }; </script>