gpt4 book ai didi

javascript - 是否可以在 Blade 模板文件中创建 Vue 单文件组件?

转载 作者:行者123 更新时间:2023-11-30 19:40:08 25 4
gpt4 key购买 nike

这是一个关于 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 特殊代码必须在进入浏览器之前使用工具转换为 native 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com