【问题标题】:How split vue single components template section in to smaller subtemplates如何将 vue 单个组件模板部分拆分为更小的子模板
【发布时间】:2017-06-11 00:54:27
【问题描述】:

我的应用程序是在 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>

我可以通过 mixin 与每个组件共享方法,但我不能以相同的方式共享“模板部分”。你如何处理这种情况?

我尝试创建组件create-reset-buttons,但我无法触发父方法,因为每个组件都封装了它的功能并且不允许修改来自子组件的道具。为了重置父表单,需要执行哪些操作。

【问题讨论】:

    标签: vuejs2 vue-component vue.js


    【解决方案1】:

    组件不允许修改props,但有wayschild 可以与parent 通信,详细解释here

    在 Vue.js 中,父子组件的关系可以概括为 props down,events up。父级通过 props 向下传递数据给子级,子级通过事件向父级发送消息。让我们看看他们接下来是如何工作的。

    How to pass props

    以下是将 props 传递给 chile 元素的代码:

    <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
        }
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 2019-07-31
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2016-09-08
      • 2012-01-09
      相关资源
      最近更新 更多