欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue單文件組件的實現(xiàn)

 更新時間:2021年06月23日 15:41:06   作者:諸葛韓信  
最近翻閱了一下vue。發(fā)覺有一個單文件組件之前基本忽視掉了。所以本文就詳細的介紹了vue單文件組件的實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下

最近翻閱了一下vue。發(fā)覺有一個單文件組件之前基本忽視掉了。vue.js中的單文件組件允許在一個文件中定義一個組件的所有內(nèi)容。也就是說,一個頁面或者是一個組件,我們想將他們捆綁在一起,那么vue的這個單文件組件可以做到。正如vue的官網(wǎng)說的,“在很多 Vue 項目中,我們使用 app.component 來定義全局組件,緊接著用 app.mount('#app') 在每個頁面內(nèi)指定一個容器元素?!边@里的組件,都是相對簡單的,而面對一個比較復(fù)雜的項目,這種方式就行不通。原因如下:

  • 全局定義 (Global definitions) 強制要求每個 component 中的命名不得重復(fù);
  • 字符串模板 (String templates) 缺乏語法高亮,在 HTML 有多行的時候,需要用到丑陋的 \;
  • 不支持 CSS (No CSS support) 意味著當 HTML 和 JavaScript 組件化時,CSS 明顯被遺漏;
  • 沒有構(gòu)建步驟 (No build step) 限制只能使用 HTML 和 ES5 JavaScript,而不能使用預(yù)處理器,如 Pug
  • (曾經(jīng)的 Jade) 和 Babel。

所有這些都可以通過擴展名為 .vue 的 single-file components (單文件組件) 來解決,并且還可以使用 webpack 或 Browserify 等構(gòu)建工具。
那么vue項目中的單文件組件需要如何創(chuàng)建呢?

構(gòu)建

npm install -D @vue/compiler-sfc

在控制臺上輸入上述的代碼,然后就會出現(xiàn)一個文件夾和另一個json文件。如下:

在這里插入圖片描述

我們要構(gòu)建單文件組件,就要自個制定文件。同時對webpack也要有一定的了解才行。
比如說,我們自己安裝一些需要的依賴。比如說,css-loader、css的預(yù)編譯處理器等等。因為需要項目對vue文件進行解析,那么vue-loader是必須的。

這些文件其實都是vue的簡單版本。比如簡單版的hello.vue文件,可以如下

在這里插入圖片描述

由此可以看見: 三個部分組成。而template這個部分是不可缺少的,其它的兩個部分,style和script還可以忽略掉。
script讓你的頁面js可以跟vue完美結(jié)合,而style可以使用預(yù)處理器來構(gòu)建簡潔和功能更豐富的組件。(這個單文件組件很像最初前端開發(fā)中的html文檔,它有自己的style標簽和script標簽,只是表現(xiàn)層使用一個template標簽。由于使用了簡單的方式,得到一個強大的分層組件(內(nèi)容/模板:,表現(xiàn):

在這里插入圖片描述

可能有的小伙伴喜歡將不同模塊拆分開來,也就是vue文檔說的關(guān)注點分離。那么沒有關(guān)系,你可以拆開那些文檔,將css和js拆開到另一個文件,之后引入進組件中。如下:

<!-- my-component.vue -->
<template>
  <div>This will be pre-compiled</div>
</template>
<script src="./my-component.js"></script>
<style src="./my-component.css"></style>

項目大致目錄如下:

在這里插入圖片描述

其中,index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Vue Simple Todo App with SFC</title>
    <link
      rel="stylesheet"
       rel="external nofollow"  rel="external nofollow" 
    />
    <link rel="stylesheet" href="/dist/main.css" rel="external nofollow"  rel="external nofollow"  />
  </head>
  <body>
    <div id="app"></div>
    <script src="/dist/main.js"></script>
  </body>
</html>

package.json

{
    "private": true,
    "scripts": {
      "dev": "webpack-dev-server",
      "build": "webpack --env.prod"
    },
    "dependencies": {
      "vue": "^3.1.1"
    },
    "devDependencies": {
      "@vue/compiler-sfc": "^3.1.1",
      "css-loader": "^3.5.2",
      "file-loader": "^6.0.0",
      "mini-css-extract-plugin": "^0.9.0",
      "stylus": "^0.54.7",
      "stylus-loader": "^3.0.2",
      "url-loader": "^4.1.0",
      "vue-loader": "^16.0.0-alpha.3",
      "vue-style-loader": "^4.1.2",
      "webpack": "^4.42.1",
      "webpack-cli": "^3.3.11",
      "webpack-dev-server": "^3.10.3"
    },
    "keywords": ["todo", "vue"],
    "name": "vue-todo-list-app-with-single-file-component",
    "description": "A simple todo list application written in Vue with Single File Component (SFC) support."
  }

webpack.config.js

const path = require("path");
const { VueLoaderPlugin } = require("vue-loader");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = (env = {}) => ({
  mode: env.prod ? "production" : "development",
  devtool: env.prod ? "source-map" : "cheap-module-eval-source-map",
  entry: [
    env.prod ? false : require.resolve(`webpack-dev-server/client`),
    path.resolve(__dirname, "./src/main.js")
  ].filter(Boolean),
  output: {
    path: path.resolve(__dirname, "./dist"),
    publicPath: "/dist/"
  },
  resolve: {
    alias: {
      // this isn't technically needed, since the default `vue` entry for bundlers
      // is a simple `export * from '@vue/runtime-dom`. However having this
      // extra re-export somehow causes webpack to always invalidate the module
      // on the first HMR update and causes the page to reload.
      vue: "@vue/runtime-dom"
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: "vue-loader"
      },
      {
        test: /\.png$/,
        use: {
          loader: "url-loader",
          options: { limit: 8192 }
        }
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: { hmr: !env.prod }
          },
          "css-loader"
        ]
      },
      {
        test: /\.stylus$/,
        use: ["vue-style-loader", "css-loader", "stylus-loader"]
      },
      {
        test: /\.pug$/,
        loader: "pug-plain-loader"
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({
      filename: "[name].css"
    })
  ],
  devServer: {
    inline: true,
    hot: true,
    stats: "minimal",
    contentBase: __dirname,
    overlay: true,
    injectClient: false,
    disableHostCheck: true
  }
});

test.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Vue Simple Todo App with SFC</title>
    <link
      rel="stylesheet"
       rel="external nofollow"  rel="external nofollow" 
    />
    <link rel="stylesheet" href="/dist/main.css" rel="external nofollow"  rel="external nofollow"  />
  </head>
  <body>
    <div id="app222">test pages</div>
    <script src="/dist/main.js"></script>
  </body>
</html>

src文件夾里邊有三個文件,App.vue main.js 和TodoItem.vue

其中:App.vue

<template>
  <div class="wrapper">
    <h1>My Todo List</h1>
    <form @submit.prevent="addTodo">
      <input type="text" name="todo-text" v-model="newTodoText" placeholder="New todo">
    </form>
    <ul v-if="todos.length">
      <TodoItem v-for="todo in todos" :key="todo.id" :todo="todo" @remove="removeTodo"/>
    </ul>
    <p class="none" v-else>Nothing left in the list. Add a new todo in the input above.</p>
  </div>
</template>

<script>
import TodoItem from "./TodoItem.vue"

let nextTodoId = 1

const createTodo = text => ({
  text,
  id: nextTodoId++
})

export default {
  components: {
    TodoItem
  },

  data() {
    return {
      todos: [
        createTodo("Learn Vue"),
        createTodo("Learn about single-file components"),
        createTodo("Fall in love ❤️")
      ],

      newTodoText: ""
    }
  },

  methods: {
    addTodo() {
      const trimmedText = this.newTodoText.trim()

      if (trimmedText) {
        this.todos.push(createTodo(trimmedText))
      }

      this.newTodoText = ""
    },

    removeTodo(item) {
      this.todos = this.todos.filter(todo => todo !== item)
    }
  }
}
</script>

<style lang="stylus">
*, *::before, *::after 
  box-sizing border-box

html, body
  font 16px/1.2 BlinkMacSystemFont, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif
  padding 10px

.wrapper
  width 75%
  margin 0 auto

form
  margin-bottom 20px

input[type="text"]
  width 100%
  padding 10px
  border 1px solid #777

ul, li
  margin 0
  padding 0

p.none
  color #888
  font-size small
</style>

main.js

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

TodoItem.vue

<template>
  <li>
    <span>{{ todo.text }}</span>
    <button @click.prevent="$emit('remove', todo)">Remove</button>
  </li>
</template>

<script>
export default {
  props: {
    todo: {
      required: true,
      type: Object
    }
  }
}
</script>


<style lang="stylus" scoped>
li
  display flex
  margin 5px 0

  span
    flex 1
  
  button
    border 1px solid orange
    background orange 
    color white
    font-size 0.8rem
    padding 2px 4px
    cursor pointer

    &:hover
      border-color #ff8100
      background #ff8100
</style>

注意
如果不懂得webpack,建議還是按照官網(wǎng)的指示,用vue的腳手架安裝基本的工具。
或者是按照我給的pakage.json放到項目上,npm install一下,安裝好最基本的環(huán)境,然后可以通過npm run dev進行本地開發(fā)。

其實,我覺得這個單文件組件用處已經(jīng)比較小。除非就是一個純js的項目,用的庫和組件都已經(jīng)非常的古老,那么這個時候用這個單文件組件來進行新的功能開發(fā),效果還是不錯的,前提是你要對vue比較熟悉。同時,我建議還是要學(xué)習一下webpack。不要對bable都一竅不通,然后還要通過node去啟動項目。

其實,用一個文件就將html/css/JavaScript分層管理,統(tǒng)一到了一個文件,著實能夠讓我們的項目看起來更加的有條理,規(guī)范性更加好。因為我們的jq時代,常常會將css混雜在html中,而且,簡單的一個點擊事件都要將它們分割開,這體驗當然沒有“分層而治”那么分明。

參考文獻:
1、https://v3.cn.vuejs.org/guide/single-file-component.html#%E5%9C%A8%E7%BA%BF%E6%BC%94%E7%A4%BA
2、https://www.cnblogs.com/houxianzhou/p/14510450.html

到此這篇關(guān)于vue單文件組件的實現(xiàn)的文章就介紹到這了,更多相關(guān)vue單文件組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vue2項目增加eslint配置代碼規(guī)范示例

    vue2項目增加eslint配置代碼規(guī)范示例

    這篇文章主要為大家介紹了vue2項目增加eslint配置代碼規(guī)范示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • VUE微信H5生成二維碼海報保存在本地相冊的實現(xiàn)

    VUE微信H5生成二維碼海報保存在本地相冊的實現(xiàn)

    本文主要介紹了VUE微信H5生成二維碼海報保存在本地相冊的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • vue如何統(tǒng)一樣式(reset.css與border.css)

    vue如何統(tǒng)一樣式(reset.css與border.css)

    這篇文章主要介紹了vue如何統(tǒng)一樣式(reset.css與border.css),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • vue實現(xiàn)excel文件導(dǎo)入導(dǎo)出操作示例

    vue實現(xiàn)excel文件導(dǎo)入導(dǎo)出操作示例

    這篇文章主要為大家介紹了vue實現(xiàn)excel文件的導(dǎo)入導(dǎo)出實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-07-07
  • vue代理和跨域問題的解決

    vue代理和跨域問題的解決

    這篇文章主要介紹了vue代理和跨域問題的解決,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • Vue實現(xiàn)的父組件向子組件傳值功能示例

    Vue實現(xiàn)的父組件向子組件傳值功能示例

    這篇文章主要介紹了Vue實現(xiàn)的父組件向子組件傳值功能,結(jié)合完整實例形式簡單分析了vue.js組件傳值的相關(guān)操作技巧,需要的朋友可以參考下
    2019-01-01
  • vue3中如何使用d3.js繪制流程圖(TS語法)

    vue3中如何使用d3.js繪制流程圖(TS語法)

    這篇文章主要給大家介紹了關(guān)于vue3中如何使用d3.js繪制流程圖的相關(guān)資料,D3.js是由javaScript語言編寫繪圖庫,其原理是通過調(diào)用一系列內(nèi)置函數(shù),生成SVG,并在網(wǎng)頁渲染,需要的朋友可以參考下
    2023-10-10
  • el-date-picker日期選擇限制范圍的實例代碼

    el-date-picker日期選擇限制范圍的實例代碼

    這篇文章主要介紹了el-date-picker日期選擇限制范圍,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-09-09
  • vue 組件之間事件觸發(fā)($emit)與event Bus($on)的用法說明

    vue 組件之間事件觸發(fā)($emit)與event Bus($on)的用法說明

    這篇文章主要介紹了vue 組件之間事件觸發(fā)($emit)與event Bus($on)的用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • vue3.x中useRouter()執(zhí)行后返回值是undefined問題解決

    vue3.x中useRouter()執(zhí)行后返回值是undefined問題解決

    這篇文章主要給大家介紹了關(guān)于vue3.x中useRouter()執(zhí)行后返回值是undefined問題的解決方法,文中通過代碼示例介紹的非常詳細,對大家學(xué)習或者使用vue3.x具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-09-09

最新評論