如何将vue单个组件模板部分拆分为较小的子模板

时间:2017-01-25 17:59:05

标签: vuejs2 vue-component vue.js

我的应用程序正在构建于vuejs @ 2有多种形式,大多数共享相同的html模板,带有添加和重置按钮。除了相同的方法,resetForm也会使" item"属性并重置表单,create方法将项目发送到后端。

<div class="row">
    <div class="action">
        <button class="btn btn-white" @click="create()">&#9998; Add</button>
        <button class="btn btn-white" @click="resetForm()">&#x274C; Reset</button>
    </div>
</div>

我可以通过mixins与每个组件共享方法,但我不能共享&#34;模板部分&#34;同样的方式。你如何处理这种情况?

我尝试创建组件create-reset-buttons,但我无法触发父方法,因为每个组件都封装了它的功能,并且不允许修改子进程中的props。需要完成哪些操作才能重置父表单。

1 个答案:

答案 0 :(得分:1)

不允许组件修改道具,但有ways个孩子可以详细解释here与父母沟通。

  

在Vue.js中,父子组件关系可以概括为道具向下,事件向上。父母通过道具将数据传递给孩子,孩子通过事件向父母发送消息。让我们看看他们接下来的工作方式。

enter image description here

How to pass props

以下是将道具传递给智利元素的代码:

<div>
  <input v-model="parentMsg">
  <br>
  <child v-bind:my-message="parentMsg"></child>
</div>

How to emit event

HTML:

<div id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>
</div>

JS:

Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})