vue.js - 如何在 ListView 中使用动态组件

标签 vue.js nativescript nativescript-vue

我正在尝试使用包含提前不知道其类型的组件的模板填充 NativeScript-Vue ListView。例如,此代码不起作用,因为 NativeScript 没有“组件”元素,但这表明我正在努力完成:

<ListView for="component in components">
    <v-template>
        <component :is="component" />
    </v-template>
</ListView>

computed: {
    components () {
        return ['Label', 'Button'];
    }
}

是的,我知道您可以在 v-template 中使用 if="",但在这种情况下,我无法提前知道需要在 ListView 中加载哪些组件。在我的例子中,我在插件中加载全局组件,这些组件将在 ListView 中引用。

最佳答案

感谢@Manoj。那些明智的话让我想到,模板不能是动态的,但 v-template 的内容可以。也许不适合所有人,但这段代码对我有用:

// App.vue

<template>
    <Page>
        <ActionBar title="Welcome to NativeScript-Vue!"/>
        <GridLayout columns="*" rows="400,*">
            <ListView ref="lv" for="item in items">
              <v-template>
                <v-component :type="item.type" :options="item.options" />
              </v-template>
            </ListView>
        </GridLayout>
    </Page>
</template>

<script lang="ts">
  import Vue from 'nativescript-vue'
  import { Component } from 'vue-property-decorator'
  import VComponent from './VComponent.vue'

  @Component({
    components: {
      VComponent
    }
  })
  export default class App extends Vue {
      get items () {
      return [
        {type: 'Label', options: [{key: 'text', value: 'I am a Label'}, {key: 'color', value:'red'}] },
        {type: 'Button', options: [{key: 'text', value:'I am a Button!'}]}
      ]
    }
  }
</script>


// VComponent.vue

<template>
  <StackLayout ref="myLayout">
  </StackLayout>
</template>

<script lang="ts">
  import Vue from 'nativescript-vue'
  import { Component, Prop } from 'vue-property-decorator'
  import { StackLayout } from 'tns-core-modules/ui/layouts/stack-layout'
  import { Label } from 'tns-core-modules/ui/label'
  import { Button } from 'tns-core-modules/ui/button'

  const classByClassName = {
    'Label': Label,
    'Button': Button
  }

  @Component
  export default class CoolTemplate extends Vue {
    @Prop() type!: string;
    @Prop() options;

    mounted () {
      if (this.type) {
        const myLayout = <StackLayout>((<Vue>this.$refs.myLayout).nativeView)
        const component = new classByClassName[this.type]
        for (var i = 0; i< this.options.length; i++) {
          const option = this.options[i];
          component[option.key] = option.value 
        }
        myLayout.addChild(component)
      }
    }

  } 
</script>

关于vue.js - 如何在 ListView 中使用动态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54602811/

相关文章:

android - ImageCache Nativescript核心模块使用方法

javascript - 如何在 CRUD 执行后改进/保持分页

vue.js - 更改 v-select 和 v-autocomplete 中的文本颜色

android - Nativescript:获取 RadListView 项目的 View

ios - 如何在 telerik nativescript 应用程序中添加 npm 模块

android - NativeScript TextView :textTransform can't update

javascript - Nativescript Vue Timepicker 与 Vuex

javascript - Vue.js 使用点击事件填充模式上的表单字段值

vue.js - 托管应用程序后 npm run production 不起作用

android - Nativescript tns 部署命令