【问题标题】:Vuejs load directive dynamicly via data propertyVuejs 通过数据属性动态加载指令
【发布时间】:2019-08-06 17:39:29
【问题描述】:

从 axios 我得到<test-component></test-component>,我想将它作为一个组件添加到example-component

现在是输出

<test-component></test-component>

改为关闭

test component

这可能吗?我该如何实现?

App.js:

import Example from './components/ExampleComponent.vue'
import Test from './components/Test.vue'
Vue.component('example-component', Example)
Vue.component('test-component', Test)
const app = new Vue({
  el: '#app'
});

示例组件:

<template>
    <div class="container">
        {{test}}
    </div>
</template>

export default {
    data() {
        return {
            test: ''
        }
    },
    created() {
        axios.get('/xxxx')
            .then(function (response) {
                this.test = response.data.testdirective
            })
            .catch(function (error) {
                // handle error
                console.log(error);
            })
            .finally(function () {
                // always executed
            });
    }
}

测试组件:

<template>
    <div class="container">
        test component
    </div>
</template>

【问题讨论】:

  • 您可能想看看this。您需要重新编译从服务器获得的模板。或者使用服务器端渲染。含义:仅运行时构建是不可能的。
  • 你应该在这种情况下将 directive 的使用更改为 component 因为 vue 中的指令有不同的用途,并且仅用作属性,例如v-forv-if

标签: vue.js vuejs2


【解决方案1】:

vuejs 的 runtime-only 构建是不可能的。您将需要配置您的设置以使用完整版本的 vuejs。 docs 使用一些构建工具(如 webpack)指定设置。

一旦 vue 模板编译器被集成到运行时。您可以使用当前的方法动态渲染组件。

还有另一种方法,它更简单一些。 你可以像这样使用dynamic components

<template>
  <div>
    <component v-if="name" :is="name"></component>
  </div>
</template>

<script>
import TestComponent from "./TestComponent.vue"
import Test2Component from "./Test2Component.vue"
import Test3Component from "./Test3Component.vue"

export default {
  component: {
    TestComponent,
    Test2Component,
    Test3Component
  },

  data() {
    return {
      name: undefined
    }
  },

  created() {
    axios.get('/xxxx')
        .then(function (response) {
            // where 'response.data.testdirective' is the components name
            // without <> e.g. "test-component", "test1-component" or "test2-component"
            this.name= response.data.testdirective
        })
        .catch(function (error) {
            // handle error
            console.log(error);
            this.name = undefined
        })
        .finally(function () {
            // always executed
        });
  }
}
</script>

如您所见,我不是即时编译组件,而是导入它们以进行预编译并通过name 动态绑定它们。无需额外设置!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-22
    • 2016-03-27
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2016-11-03
    相关资源
    最近更新 更多