在laravelblade模板中显示vue组件

Display vue component in laravel blade template

我在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
        }
    }

这很好。他们在 blade 文件中计算表格值。但是我如何显示总数呢?

我想在 blade 文件中显示“total”。我怎样才能访问它?当我使用 @{{ total }} 时出现此错误:

app.js:36519 [Vue warn]: Property or method "total" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

通常您会为此使用 template interpolations

类似于 {{ form.total }},在 Blade 模板中,为了克服 {{ 的用法,它将是:

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

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

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

虽然这会起作用,但在您的情况下,我建议在 pricequantity 中使用 v-model 并创建 total 作为 computed property。这将是一种更好地使用 Vue 功能的方法(并且代码更少,是的):

const app = new Vue({
    el: '#item',
    data() {
        return {
            form: {
                price: 1,
                quantity: 1,
                total: 1
            }
        }
    },
    computed: {
        total() {
            return this.form.price * this.form.quantity
        }
    }
});
<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>