vue3 emit事件
<div id="vm"> <div>子组件点击时:{{count}}</div> <blog-post @myaddevent='fuaddevent'></blog-post> </div> <script type="module"> import * as obj from './main.js' const app = Vue.createApp({ data() { return { count: 0 } }, methods: { fuaddevent(data) { this.count += data; } } }); app.component('blog-post', obj.btn1) const vm = app.mount('#vm'); </script>
main.js
const btn1 = { template: `<button @click="add(1)">增加</button>`, methods: { add(num) { this.$emit('myaddevent',num) } } } export { btn1 }
v-model子传父
<div id="vm"> <div>{{bar}}</div> <my-component v-model:foo="bar"></my-component> </div> <script type="module"> import * as obj from './main.js' const app = Vue.createApp({ data(){ return{ bar:"" } } }); app.component('my-component', obj.btn1) const vm = app.mount('#vm'); </script>
main.js
const btn1 = { props: { foo: String }, template: ` <input type="text" :value="foo" @input="$emit('update:foo', $event.target.value)">`, } export { btn1 }