Vue动态组件component标签怎么使用

发布时间:2022-08-24 17:49:28 作者:iii
来源:亿速云 阅读:321

这篇文章主要介绍“Vue动态组件component标签怎么使用”,在日常操作中,相信很多人在Vue动态组件component标签怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Vue动态组件component标签怎么使用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

简介

说明

在Vue中,可以通过component标签的is属性动态指定标签,例如:

<component :is="componentName"></component>

此时,componentName的值是什么,就会引入什么组件。

示例

路由设置

router/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import Parent from '../components/Parent'
 
Vue.use(VueRouter)
 
const routes = [
  {
    path: '/',
    name: 'Parent',
    component: Parent
  }
]
 
const router = new VueRouter({
  routes
})
 
export default router

父组件

components/Parent.vue

<template>
  <div class="outer">
    <h3>这是父组件</h3>
    <component :is="componentName" :propA="propAValue"></component>
  </div>
</template>
 
<script>
import ChildA from './ChildA'
import ChildB from './ChildB'
 
export default {
  name: 'Parent',
  components: { ChildA, ChildB },
  data () {
    return {
      componentName: 'ChildB',
      propAValue: 'aaa'
    }
  }
}
</script>
 
<style scoped>
.outer {
  margin: 20px;
  border: 2px solid red;
  padding: 20px;
}
</style>

子组件

components/ChildA.vue

<template>
  <div class="outer">
    <h4>这是ChildA</h4>
    <div>传入进来的propA值为:{{propA}}</div>
  </div>
</template>
 
<script>
export default {
  name: 'ChildA',
  props: ['propA']
}
</script>
 
<style scoped>
.outer {
  margin: 20px;
  border: 2px solid blue;
  padding: 20px;
}
</style>

components/ChildA.vue

<template>
  <div class="outer">
    <h4>这是ChildB</h4>
    <div>传入进来的propA值为:{{propA}}</div>
  </div>
</template>
 
<script>
export default {
  name: 'ChildB',
  props: ['propA']
}
</script>
 
<style scoped>
.outer {
  margin: 20px;
  border: 2px solid blue;
  padding: 20px;
}
</style>

测试

访问:http://localhost:8080/

Vue动态组件component标签怎么使用

到此,关于“Vue动态组件component标签怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. Vue中怎么动态创建注册component
  2. vue19如何组建Vue.extend component、组件模版、动态组件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue component

上一篇:Intellij IDEA怎么根据maven依赖名查找它是哪个pom.xml引入的

下一篇:docker网络、部署集群和打包镜像问题怎么解决

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》