html :引入 publicmsg 与 acceptmsg 自定义组件 (自定义组件名称必须小写)
<body>
<div id="app">
<publicmsg></publicmsg>
<acceptmsg></acceptmsg>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script type="module" src="./js/templates.js"></script>
<script src="https://unpkg.com/mitt/dist/mitt.umd.js"></script>
</body>
js: 通过 emit(‘事件名称’,‘传递的参数’) 发布事件 ,on(‘事件名称’,回调函数) 监控事件
<script>
const emitter = window.mitt()
const app = Vue.createApp({})
app
.component('publicmsg', {
template:
'<div><input type="text" ref="publicMessage"/><button @click="publicMsg()">发布</button></div>',
methods: {
publicMsg () {
emitter.emit('messages', this.$refs.publicMessage.value)
}
}
})
.component('acceptmsg', {
data () {
return { acceptMesage: '' }
},
template: '<div><p>接收:{{acceptMesage}}</p></div>',
mounted () {
emitter.on('messages', msg => {
this.acceptMesage = msg
})
}
})
.mount('#app')
</script>
通过 component 标签 及 :is 属性动态选择显示的组件,keep-alive 标签可以使得组件在切换时,原组件被隐藏而不是被删除
html :
<body>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script type="module" src="./js/11.动态组件.js"></script>
<div id="app">
<keep-alive>
<component :is="chooseValue"></component>
</keep-alive>
<select v-model="chooseValue">
<option value="component1">组件1</option>
<option value="component2">组件2</option>
<option value="component3">组件3</option>
</select>
</div>
</body>
js :
<script>
const app = Vue.createApp({
data () {
return { chooseValue: 'component1' }
},
components: {
component1: {
template: '<div><button>组件1</button><input type="text"/></div>'
},
component2: {
template: '<div><button>组件2</button><input type="text"/></div>'
},
component3: {
template: '<div><button>组件3</button><input type="text"/></div>'
}
}
}).mount('#app')
</script>
结果演示:
A:当前为组件1: 输入文字后
-------------------------------------------------------------------------------------------
B:切换到组件2:
-------------------------------------------------------------------------------------------
C:切回组件1: 组件1输入的文字没有消失