这是一个关于 Laravel 和 Vue 的问题。
在过去的一年里,我已经尝试过几次在 Blade 模板中创建 Vue 组件,但我一直无法让它工作。我觉得这是可能的,但我还没有找到有人这样做的例子。每次尝试执行此操作时,我都会在 Google 上进行搜索,但找不到示例。
而不是创建一个 Vue 单文件组件 (SFC) 并从 Blade 模板中调用它,如下所示:
@extends('layouts.root')
@section('title', 'Some Page')
@section('content')
<my-component :some-state="{{ $someData->toJson() }}"></my-component>
@endsection
我想在 Blade 模板中创建 Vue 组件,如下所示:
resources/views/some/page.blade.php
@extends('layouts.root')
@section('title', 'Some Page')
@section('content')
<div>
<my-component
:some-state="{{ $someData->toJson() }}"
></my-component>
</div>
@endsection
<template>
<div>
{{ $object }}
</div>
</template>
<script>
export default {
name: 'my-component',
props: {
type: Object,
required: true,
},
data() {
return {};
},
computed: {},
methods: {},
}
</script>
<style scoped>
.div { background-color: red; }
</style>
我正在寻找一种方法来从 page.blade.php
文件中完成所有这些操作。
我已经很接近了吗,或者甚至有可能吗?
我这样做的动机是我有大约 30 个 Blade 模板,如果我决定要在其中包含一些客户端状态或使用 JavaScript 而不是 Blade(对于诸如 v-if
之类的东西)而不是 @if () @endif
),那么我需要为这些 Vue 组件创建大约 30 个以上的文件。
最好省略文件创建步骤,并使用这些 Blade 模板文件从 Laravel 传递数据,并在其中提供功能齐全的 Vue SFC。也许这是一个疯狂的想法,惯用的选择是在 Laravel 的文件夹 resources/assets/js/components
中制作更多 Vue 组件,但我只是想知道这是否可能。谁能阐明这一追求?
最佳答案
考虑到您使用的是 Vue 的单文件组件形式(模板、脚本、样式),您不能这样使用它,因为 Vue 特殊代码在进入浏览器之前必须使用工具转换为原生 JavaScript。
如果您想使用,还有另一种创建组件的方法,但不是首选方法:
在这里,我展示了如何完成它的基本想法,但您必须根据您的需要进行编辑。
<div id="vue-app">
<todo-component></todo-component>
</div>
//then create component by using x-template way
<script type="x-template" id="todo-component">
<div>
<span :title="Your normal Vue codes title">{{text}}</span>
</div>
</script>
//and add component to Vue.
<script>
Vue.component('todo-component', {
template: '#todo-component',
data: function () {
return {
text: 'Your normal Vue codes here'
};
},
});
var app = new Vue({
el: '#vue-app'
});
</script>
关于javascript - 是否可以在 Blade 模板文件中创建 Vue 单文件组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55488734/