编写 Vue 组件

新安装的 Laravel 应用在 resources/js/components 目录默认包含一个 ExampleComponent.vue Vue 组件。 ExampleComponent.vue单文本 Vue 组件 的实例,定义了自身的 JavaScript 和 HTML 模版。单文本组件为构建 JavaScript 驱动的应用提供了便利。这个实例组件已经在 app.js 文件中注册:

Vue.component(
    'example-component',
    require('./components/ExampleComponent.vue')
);

想要在应用中使用组件,只需要把它放在 HTML 模版中即可。例如,运行 make:auth Artisan 命令生成应用的认证和注册页面后,就可以把它置入 home.blade.php Blade 模版:

@extends('layouts.app')

@section('content')
    <example-component></example-component>
@endsection

{tip} 谨记,每次修改 Vue 组件后,都应该运行 npm run dev 命令。或者,运行 npm run watch 命令监听组件的每次修改,进行自动编译。

需要 Vue 组件更多信息的话,可以阅读 Vue 官方文档, 它对整个 Vue 框架进行了充分、易读的综述。

以上内容是文档翻译过来的,可以看出要想在 Laravel 中 使用Vue 大致需要 4 步。

  • resources/js/components 中编写 .vue 组件
  • app.js 中注册
  • 视图中应用组件
  • 编译运行 npm run dev 命令

接下来基于以上步骤编写一个自己的组件

创建组件

resources/js/components 中编写 HelloWorld.vue 组件

<style scoped>
</style>

<template>
    <div class="flex-center position-ref full-height">
        <p>hello world</p>
    </div>
</template>

<script>
    export default {}
</script>

注册组件

app.js 中注册该组件

.
.
.
Vue.component('hello-world', require('./components/HelloWorld.vue'));

const app = new Vue({
    el: '#app'
});

使用组件

在视图中使用组件

.
.
.
<body>
    <div id="app">
        <hello-world></hello-world>
    </div>
    <script src="/js/app.js"></script>
</body>
.
.
.

编译前端资源

npm run dev

关于极客返利

极客返利 是由我个人开发的一款网课返利、返现平台。包含 极客时间返现、拉勾教育返现、掘金小册返现、GitChat返现。目前仅包含这几个平台。后续如果有需要可以考虑其他平台。 简而言之就是:你买课,我返现。让你花更少的钱,就可以买到课程。

https://geekfl.com

https://geek.laravelcode.cn

版权许可

本作品采用 知识共享署名 4.0 国际许可协议 进行许可。

转载无需与我联系,但须注明出处,注明文章来源 Laravel 项目中编写 Vue 组件

联系我

编程怪事
暂无回复
0 / 180