【问题标题】:how to render component from a component in vue js如何从 vue js 中的组件渲染组件
【发布时间】:2018-10-19 01:02:20
【问题描述】:

我有一个带有以下模板的组件:

    <div v-for:"item in store" v-bind:key="item.type">
       <a>{{item.type}}</a>
    </div>

我有另一个名为“StoreComponent”的组件 单击第一个组件中的元素时,我想清除当前组件并显示 StoreComponent 并能够将 item.type 传递给 StoreComponent。

我不想使用 router-link 或 router.push,因为我不想创建新的 url,而是根据 item.type 值用新的 url 覆盖当前组件。

StoreComponent.vue

     export default{
        name: 'StoreComponent',
        props: ['item'],
        data: function () {
          return {
             datum: this.item
           }
        },
       methods: {
          //custom methods
       }
    }

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vue-router


    【解决方案1】:

    您可以使用dynamic components 并将item-type 作为prop 传递。

    Vue.component('foo', {
      name: 'foo',
      template: '#foo'
    });
    
    Vue.component('bar', {
      name: 'bar',
      template: '#bar',
      props: ['test']
    }); 
    
    new Vue({
      el: "#app",
      data: {
        theComponent: 'foo',  // this is the 'name' of the current component
        somethingWeWantToPass: {
        	test: 123 // the prop we are passing
        },
      },
      methods: {
        goFoo: function() {
        	this.theComponent = 'foo';
        },
        goBar: function() {
        	this.theComponent = 'bar';
        },
      }
    })
    <script src="https://unpkg.com/vue"></script>
    <div id="app">
      <button @click="goFoo">Foo</button>
      <button @click="goBar">Bar</button>
      <component :is="theComponent" v-bind="somethingWeWantToPass"></component>
    </div>
    
    
    <template id="foo">
      <div>
        Foo
      </div>
    </template>
    
    <template id="bar">
      <div>
        Bar
        <div>This is a prop:  {{ this.test }}</div>
      </div>
    </template>

    【讨论】:

    • 那么对于 webpack 项目,你不应该在每个 .vue 文件中只有一个模板和脚本标签吗?
    • 并且要绑定的道具是动态的,具体取决于默认模板,例如在您的情况下它是 foo 因此必须根据正在处理的当前项目从 foo 传递数据。
    • @developer 是的,每个组件只有一个模板。所以我会有三个组件。跟踪选定项类型的值并保存component 标记的包装器。然后是其他两个组件StoreComponent 和您选择项目类型的组件。然后,当您选择项目类型时,您需要向包装组件发送一个事件,以便它知道并可以将正确的值传递给StoreComponent。
    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 2018-05-04
    • 2021-07-16
    • 2017-10-24
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2017-11-23
    相关资源
    最近更新 更多