将vue.js模板分成文件

时间:2018-02-24 23:29:20

标签: javascript vue.js

我想知道Vue.js是否有办法制作这段代码:

<template v-if="type === 'login'">
  <label>Username</label>
  <input placeholder="Enter your username" key="username-input">
</template>

<template v-if="type === 'subscribe'">
  <label>Email</label>
  <input placeholder="Enter your email address" key="email-input">
</template>

看起来像这样:

<template type="login" />

<template type="subscribe" />

<template id="login">
  <label>Username</label>
  <input placeholder="Enter your username" key="username-input">
</template>

<template id="subscribe">
  <label>Email</label>
  <input placeholder="Enter your email address" key="email-input">
</template>

所以我们可以通过他们的ID调用模板

在我的情况下,我想在事件中使用它:

<template v-if="type === 'new_user'">
 <span>welcome {{ username }}</span>
</template>

<template v-if="type === 'user_confiremd'">
 <span>You have full access {{ username }}</span>
</template>

我想做这样的事情:

<template v-for="event in events" :event="event" />

2 个答案:

答案 0 :(得分:2)

这听起来像是不良行为的开始......

您需要创建两个组件并使用类型变量的相关信息。

您可以通过路由或仅动态组件来控制组件。

这样的事: <component :is="type" />

Refernces:

答案 1 :(得分:1)

如果您想有条件地使用某些模板,以下是Vue2's dynamic components如何使用的示例:

&#13;
&#13;
new Vue({
  el: '#app',
  data: {
    type: 'login',
    email: 'email.sync@example.com',
    dataFromChildren: {parentData: {email: 'vbind@example.com'}}
  },
  components: {
    login: {
      template: '#login',
      props: ['email'],
      data: function() { return { watchedEmail: this.email } },
      watch: { watchedEmail: function() { this.$emit('update:email', this.watchedEmail); } }
    },
    subscribe: {
      template: '#subscribe',
      props: ['parentData']
    }
  }
});
&#13;
<script src="https://unpkg.com/vue"></script>

<template id="login">
  <div>
    <label>Username</label>
    <input placeholder="Enter your username" key="username-input" v-model="watchedEmail">
  </div>
</template>

<template id="subscribe">
  <div>
    <label>Email</label>
    <input placeholder="Enter your email address" key="email-input" v-model="parentData.email">
  </div>
</template>

<div id="app">
  <component v-bind:is="type" :email.sync="email" v-bind="dataFromChildren"></component>

  <hr>
  <button @click="type = 'login'">login template</button>
  <button @click="type = 'subscribe'">subscribe template</button>
  
  <p>Edited via e-mail.sync [login component] (good practice): {{ email }}</p>
  <p>Edited via nested props [subscribe component] (bad practice): {{ dataFromChildren }}</p>
</div>
&#13;
&#13;
&#13;

我在这里看到的一个缺点是你的模板必须有一个根组件(否则你会得到错误组件模板应该只包含一个根元素。),这是Vue的要求。

另一件事是模板是实际的组件,所以要将数据传递给它们,你必须拥有道具和所有。上面的代码显示了发送该数据并将其恢复的两种方式。我推荐:e-mail.sync替代方案,这是本案例中的最佳做法。