在laravel刀片模板中显示vue组件

时间:2018-04-13 16:41:43

标签: php laravel vue.js blade

我在app.js做一个简单的计算。它只是将产品价格乘以数量。我想在laravel中显示总值,因此用户可以预览他们的订单。

app.js

const app = new Vue({
    el: '#item',
    data() {
        return {
            form: {
                price: 0,
                quantity: 0,
                total: 0
            }
        }
    },
    methods: {
        updatePrice(event) {
            this.form.price = event.target.value;
            this.form.total = this.form.price * this.form.quantity
        },
        updateQuantity(event) {
            this.form.quantity = event.target.value;
            this.form.total = this.form.price * this.form.quantity
        }
    }

这很好。他们计算刀片文件中的表单值。但我怎么能显示总数呢?

total price

我想在刀片文件中显示“total”。我该如何访问?当我使用@{{ total }}时,我收到此错误:

  

app.js:36519 [Vue警告]:未定义属性或方法“total”   实例,但在渲染期间引用。确保这一点   属性是反应性的,可以是数据选项,也可以是基于类的   组件,通过初始化属性。

1 个答案:

答案 0 :(得分:6)

通常情况下,您会使用template interpolations

{{ form.total }}这样的,在Blade模板中,为了克服{{的使用,它将是:

<div id="item">
  <p>Total is: @{{ form.total }}</p>
</div>

或者,您可以更改Vue的分隔符并解决此问题。例如(delimiters: ['!{', '}!'],):

&#13;
&#13;
const app = new Vue({
    el: '#item',
    delimiters: ['!{', '}!'],
    data() {
        return {
            form: {
                price: 1,
                quantity: 1,
                total: 1
            }
        }
    },
    methods: {
        updatePrice(event) {
            this.form.price = event.target.value;
            this.form.total = this.form.price * this.form.quantity
        },
        updateQuantity(event) {
            this.form.quantity = event.target.value;
            this.form.total = this.form.price * this.form.quantity
        }
    }
});
&#13;
<script src="https://unpkg.com/vue"></script>

<div id="item">
  <p>Total is: !{ form.total }!</p>
  price: <input @input="updatePrice"><br>
  quantity: <input @input="updateQuantity"><br>
</div>
&#13;
&#13;
&#13;

虽然这样可行,但在您的情况下,我建议不要直接处理事件,而是建议在v-modelprice中使用quantity并将total创建为{{3} }}。这将是一种更好地使用Vue功能的方法(并且代码更少,是的):

&#13;
&#13;
const app = new Vue({
    el: '#item',
    data() {
        return {
            form: {
                price: 1,
                quantity: 1,
                total: 1
            }
        }
    },
    computed: {
        total() {
            return this.form.price * this.form.quantity
        }
    }
});
&#13;
<script src="https://unpkg.com/vue"></script>

<div id="item">
  <p>Total is: {{ total }}</p>
  price: <input v-model="form.price"><br>
  quantity: <input v-model="form.quantity"><br>
</div>
&#13;
&#13;
&#13;