vue中使用动态组件

1.怎么使用动态组件?

  • 1.< component >标签
  • 2.:is属性
  • 3.动态组件能自动切换组件,进行内容渲染
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>vue动态组件</title>
	<script src="./vue.js"></script>
</head>
<body>
	<div id="app">
		<component :is="type"></component>
		<button @click="headleBtnClick">change</button>
	</div>
	<script>
		Vue.component('child-one',{
			template: '<div v-once>child-one</div>'
		})

		Vue.component('child-two',{
			template: '<div v-once>child-two</div>' //动态组件每次回销毁一个组件,再创建另一个组件进行显示。  
			//v-once指令可以将静态内容加载入内存中,  
		})

		var vm = new Vue({
			el: '#app',
			data: {
				type: 'child-one'
			},
			methods: {
				headleBtnClick: function(){
					this.type = (this.type === 'child-one'?'child-two' : 'child-one' )
				}
			}
		})
	</script>
</body>
</html>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3,你可以使用动态组件来实现组件动态渲染。你可以使用`<component>`标签,并通过`v-bind:is`属性来决定要渲染的实际组件。这个`is`属性可以是一个字符串,可以是HTML标签名,也可以是已注册的组件名。另外,你也可以直接将组件定义传递给`is`属性,而不是组件的名称。内置组件都可以传递给`is`属性,但如果你想通过名称传递组件,则需要先对其进行注册。如果将组件本身传递给`is`属性而不是其名称,则不需要注册。[2] 具体实现时,你可以在页面上注册需要使用组件,然后使用`<component>`标签来动态渲染组件。你可以通过`v-bind:is`属性来指定要渲染的组件名称或组件定义。[3] 以下是一个示例代码,展示了如何在Vue 3使用动态组件: ```html <template> <div> <button @click="switchComponent('A')">A组件</button> <button @click="switchComponent('B')">B组件</button> <button @click="switchComponent('C')">C组件</button> <component :is="currentComponent"></component> </div> </template> <script setup> import { ref } from 'vue'; import AComponent from './components/AComponent.vue'; import BComponent from './components/BComponent.vue'; import CComponent from './components/CComponent.vue'; const currentComponent = ref(''); const switchComponent = (componentName) => { currentComponent.value = componentName; }; </script> ``` 在上面的代码,我们使用`<component>`标签来动态渲染组件。通过`v-bind:is`属性绑定了`currentComponent`变量,该变量保存了当前要渲染的组件名称。当点击不同的按钮时,调用`switchComponent`方法来切换要渲染的组件。[1] 希望这个例子能帮助你理解如何在Vue 3使用动态组件。如果你有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值