主頁 > 企業開發 > Vue 腳手架編程

Vue 腳手架編程

2022-10-31 08:42:57 企業開發

1.1 初始化腳手架

1.1.1 說明

  1. Vue 腳手架是 Vue 官方提供的標準化開發工具(開發平臺)
  2. 最新的版本是 4.x
  3. 檔案

1.1.2 具體步驟

  1. 第一步(僅第一次執行):全域安裝 @vue/cli

    npm install -g @vue/cli
    
  2. 第二步: 切換到要創建專案的目錄 ,然后使用命令創建專案

    vue create xxxx
    

    xxxx: 專案名

  3. 第三步:啟動專案

    npm run serve
    
  4. 備注:

    1. 如出現:下載緩慢請配置淘寶鏡像:

      npm config set registry https://registry.npm.taobao.org
      
    2. Vue 腳手架隱藏了所有 webpack 相關的配置,若想查看具體的 webpack配置,請執行:

      vue inspect > output.js
      

1.1.3 模板專案的結構

├──node_modules
├──public
│ ├──favicon.ico:頁簽圖示
│ └──index.html:主頁面
├──src
│ ├──assets:存放靜態資源
│ │ └──logo.png
│ │──component:存放組件
│ │ └──HelloWorld.vue
│ │──App.vue:匯總所有組件
│ │──main.js:入口檔案
├──.gitignore:git版本管制忽略的配置
├──babel.config.js:babel的組態檔
├──package.json:應用包組態檔
├──README.md:應用描述檔案
├──package-lock.json:包版本控制檔案

1.1.4 不同版本的 Vue

  1. vue.jsvue.runtime.xxx.js 的區別:
    1. vue.js 是完整版的 Vue,包含:核心功能 + 模板決議器,
    2. vue.runtime.xxx.js 是運行版的 Vue,只包含:核心功能;沒有模板決議器
  2. 因為 vue.runtime.xxx.js 沒有模板決議器,所以不能使用 template 這個配置項,需要使用 render 函式接收到的 createElement 函式去指定具體內容

1.1.5 vue.config.js 組態檔

  1. 使用 vue inspect > output.js 可以查看到Vue腳手架的默認配置,

  2. 使用 vue.config.js 可以對腳手架進行個性化定制,詳情

1.2 ref

1.2.1 使用說明

  1. 被用來給元素或子組件注冊參考資訊(id 的替代者)
  2. 應用在 html 標簽上獲取的是真實 DOM 元素,應用在組件標簽上是組件實體物件(vc
  3. 使用方式:
    1. 打標識:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
    2. 獲取:this.$refs.xxx

1.3 props

1.3.1 使用說明

  1. 功能:讓組件接收外部傳過來的資料

  2. 傳遞資料:<Demo name="xxx"/>

  3. 接收資料:

    1. 第一種方式(只接收):props:['name']

    2. 第二種方式(限制型別):props:{name:String}

    3. 第三種方式(限制型別、限制必要性、指定默認值):

      props:{
      	name:{
      	type:String, //型別
      	required:true, //必要性
      	default:'老王' //默認值
      	}
      }
      

    備注:props 是只讀的,Vue 底層會監測你對 props 的修改,如果進行了修改,就會發出警告,若業務需求確實需要修改,那么請復制 props 的內容到 data 中一份,然后去修改 data 中的資料,

1.3.2 代碼示例

父組件 App 中使用子組件 Student,并傳引數

<template>
<div id="app">
    <!-- 注意:屬性前面有沒有加 : 的區別,沒加就是表示傳的引數是字串,加了就是表示具體的型別值 -->
    <!-- <Student studentName="張三" studentSex="男" studentAge="18"/> -->
    <hr />
    <Student studentName="張三" studentSex="男" :studentAge="18"/>
    <hr />
    <Student  studentSex="男" :studentAge="20"/>

    </div>
</template>
<script>
    import Student from "./components/Student.vue";

    export default {
        components: { Student }
    };
</script>

Student 組件接收父組件傳來的引數

<template>
  <div>
    <h2>{{ msg }}</h2>
    <h2>學生姓名: {{ studentName }}</h2>
    <h2>學生性別: {{ studentSex }}</h2>
    <!-- <h2>學生年齡: {{ studentAge + 1 }}</h2> -->
    <h2>學生年齡: {{ age + 1 }}</h2>
    <button @click="addAge">點我年齡 +10 </button>
  </div>
</template>

<script>
export default {
  name: "Student",
  // 接收引數的簡要寫法
  // props: ['studentName', 'studentSex', 'studentAge'],

  // 接受引數 + 指定型別的寫法
  // props: {
  //   studentName: String,
  //   studentSex: String,
  //   // 指令型別為數值型別,當傳入的型別不是數值型別時就會報錯
  //   // Expected Number with value 18, got String with value "18".
  //   studentAge: Number, 
  // },

  // 接收引數 + 指定型別 + 指定是否必傳 + 指定默認值
  props: {
    studentName: {
      // 指定型別是字串
      type: String,
      // 指定默認值
      default: "李四"
    },
    studentSex: {
      type: String,
      // 指定必傳
      required: true
    },
    studentAge: {
      type: Number
    }
  },
  
  data() {
    return {
      msg: "我是一名學生",
      age: this.studentAge
    };
  },

  methods: {
    addAge() {
      // props 是只讀的,Vue 底層會監測你對 props 的修改,如果進行了修改,就會發出警告,若業務需求確實需要修改,那么請復制 props 的內容到 data 中一份,然后去修改 data 中的資料,
      // 警告 
      // Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders.
      // this.studentAge += 10;
      this.age += 10
    }
  }
};
</script>

1.4 混入

1.4.1 使用說明

  1. 功能:可以把多個組件共用的配置提取成一個混入物件

  2. 使用方式:

    第一步定義混入:

    {
        data(){....},
        methods:{....}
        ....
    }
    

    第二步使用混入:
    ? - 全域混入:Vue.mixin(xxx)
    ? - 區域混入:mixins:['xxx']

1.4.2 代碼示例

定義混入 mixin.js

// 定義一個混入配置資訊
// 說明:如果混入中配置的資料、方法,在組件中有同樣的資料定義、方法名稱,會加載組件中的資料和方法,混入中的資料和方法就不起作用
const mixin1 = {
    data() {
        return {
            x: 200,
            y: 100
        }
    },
    methods: {
        showName() {
            alert(this.name)
        }
    },
}
// 說明:生命周期中的函式,如果混入、組件中都有配置的話,二者都會執行
const mixin2 = {
    mounted() {
        console.log("mixin 中的 mounted... ")
    },
}

export {
    mixin1,
    mixin2
}

在組件中使用混入:

<template>
  <div>
    <h2>學校名稱: {{ name }}</h2>
    <h2>學校地址: {{ address }}</h2>
    <button @click="showName">點我提示資訊</button>
  </div>
</template>

<script>
// 引入混入
import { mixin1 } from "@/mixin";

export default {
  name: "School",
  // 混入配置項
  mixins: [mixin1],
  data() {
    return {
      name: "北京大學",
      address: "北京",
    };
  },
  methods: {
    // showName() {
    //   alert(this.name);
    // },
  },
};
</script>
<template>
  <div>
    <h2>學生姓名: {{ name }}</h2>
    <h2>學生性別: {{ sex }}</h2>
    <h2>學生年齡: {{ age }}</h2>
    <button @click="showName">點我提示資訊</button>
  </div>
</template>

<script>
// 引入混入
import { mixin1, mixin2 } from "../mixin";
export default {
  name: "Student",
  mixins: [mixin1, mixin2],

  data() {
    return {
      name: "張三",
      sex: "男",
      age: 20,
      x: 1000,
    };
  },
  methods: {
    showName() {
      console.log("student... ");
      alert(this.name + "hello world");
    },
  },
  mounted() {
    console.log("student 中的 mounted... ");
  },
};
</script>

1.5 插件

1.5.1 使用說明

  1. 功能:用于增強 Vue

  2. 本質:包含 install 方法的一個物件,install 的第一個引數是 Vue,第二個以后的引數是插件使用者傳遞的資料,

  3. 定義插件:

    物件.install = function (Vue, options) {
        // 1. 添加全域過濾器
        Vue.filter(....)
    
        // 2. 添加全域指令
        Vue.directive(....)
    
        // 3. 配置全域混入(合)
        Vue.mixin(....)
    
        // 4. 添加實體方法
        Vue.prototype.$myMethod = function () {...}
        Vue.prototype.$myProperty = xxxx
    }
    
  4. 使用插件:Vue.use()

1.5.2 代碼示例

定義插件 plugins.js

export default {
    install(Vue) {
        console.log(Vue, "@@@@@");

        // 全域定義過濾器
        Vue.filter("strSlice", function (value) {
            return value.slice(0, 4)
        })

        // 全域定義指令
        Vue.directive("fbind", {
            // 指令與元素成功系結時 一上來
            bind(element, binding) {
                element.value = https://www.cnblogs.com/codechen8848/archive/2022/10/30/binding.value
            },
            // 指令所在元素插入頁面時
            inserted(element, binding) {
                element.focus()
            },
            // 指令所在模板被重新決議時
            updated(element, binding) {
                element.value = binding.value
            },
        })
        // 給 Vue 原型上添加一個方法 vm、vc 都能使用
        Vue.prototype.hello = () => {
            console.log("hello world ");
        }
    },

}

main.js 中使用插件

// 引入插件
import plugins from './plugins'

// 使用插件
Vue.use(plugins)

1.6 scoped 樣式

  1. 作用:讓樣式在區域生效,防止沖突,

  2. 寫法:

    <style scoped>
      .demo {
        background-color: orange;
        // less 與 css 的一個區別就是 less 可以疊加寫,css 不可以
        .title {
          font-size: 40px;
        }
      }
    </style>
    

1.7 組件化編碼流程

  1. 組件化編碼流程:
    1. 拆分靜態組件:組件要按照功能點拆分,命名不要與 html 元素沖突,
    2. 實作動態組件:考慮好資料的存放位置,資料是一個組件在用,還是一些組件在用:
      1. 一個組件在用:放在組件自身即可,
      2. 一些組件在用:放在他們共同的父組件上(狀態提升),
      3. 實作互動:從系結事件開始,
  2. props 適用于:
    1. 父組件 ==> 子組件 通信
    2. 子組件 ==> 父組件 通信(要求父先給子一個函式)
  3. 使用 v-model 時要切記:v-model 系結的值不能是 props 傳過來的值,因為 props 是不可以修改的!
  4. props 傳過來的若是物件型別的值,修改物件中的屬性時 Vue 不會報錯,但不推薦這樣做,

1.8 webStorage

1.8.1 使用說明

  1. 存盤內容大小一般支持 5MB 左右(不同瀏覽器可能還不一樣)

  2. 瀏覽器端通過 Window.sessionStorageWindow.localStorage 屬性來實作本地存盤機制

  3. 相關API:

    1. xxxxxStorage.setItem('key', 'value');
      該方法接受一個鍵和值作為引數,會把鍵值對添加到存盤中,如果鍵名存在,則更新其對應的值

    2. xxxxxStorage.getItem('person');
      ?該方法接受一個鍵名作為引數,回傳鍵名對應的值

    3. xxxxxStorage.removeItem('key');
      ?該方法接受一個鍵名作為引數,并把該鍵名從存盤中洗掉

    4. xxxxxStorage.clear()

      該方法會清空存盤中的所有資料

  4. 備注:

    1. SessionStorage 存盤的內容會隨著瀏覽器視窗關閉而消失
    2. LocalStorage 存盤的內容,需要手動清除才會消失
    3. xxxxxStorage.getItem(xxx) 如果 xxx 對應的 value 獲取不到,那么 getItem 的回傳值是 null
    4. JSON.parse(null) 的結果依然是 null

1.8.2 代碼示例

LocalStorage

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>localStorage 瀏覽器本地存盤</title>
</head>
<body>
    <div>
        <h2>localStorage 瀏覽器本地存盤</h2>
        <button onclick="save()">點我保存一個資料</button>
        <button onclick="read()">點我讀取一個資料</button>
        <button onclick="remove()">點我洗掉一個資料</button>
        <button onclick="clearAll()">點我清空資料</button>
    </div>

    <script type="text/javascript">
        let person = {name: "張三", age: 19}

        // localStorage 保存資料時最終都是 字串
        function save() {
            // 保存字串
            localStorage.setItem("name", "張三")
            // 保存數字
            localStorage.setItem("age", 18)
            // 保存物件資料
            // localStorage.setItem("person", person)
            localStorage.setItem("person", JSON.stringify(person))
        }

        function read() {
            // 讀取字串
            console.log(localStorage.getItem("name"))
            // 讀取數字
            console.log(localStorage.getItem("age"))
            // 讀取物件
            console.log(localStorage.getItem("person"))
            console.log(JSON.parse(localStorage.getItem("person")))
        }

        function remove() {
            // 洗掉字串
            localStorage.removeItem("name")
            // 移除數字
            localStorage.removeItem("age")
            // 移除物件
            localStorage.removeItem("person")
        }

        function clearAll() {
            console.log("clear...");
            localStorage.clear()
        }
    </script>
</body>
</html>

SessionStorage

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>sessionStorage 瀏覽器本地存盤</title>
</head>
<body>
    <div>
        <h2>sessionStorage 瀏覽器本地存盤</h2>
        <button onclick="save()">點我保存一個資料</button>
        <button onclick="read()">點我讀取一個資料</button>
        <button onclick="remove()">點我洗掉一個資料</button>
        <button onclick="clearAll()">點我清空資料</button>
    </div>

    <script type="text/javascript">
        let person = {name: "張三", age: 19}

        // sessionStorage 保存資料時最終都是 字串
        function save() {
            // 保存字串
            sessionStorage.setItem("name", "張三")
            // 保存數字
            sessionStorage.setItem("age", 18)
            // 保存物件資料
            // sessionStorage.setItem("person", person)
            sessionStorage.setItem("person", JSON.stringify(person))
        }

        function read() {
            // 讀取字串
            console.log(sessionStorage.getItem("name"))
            // 讀取數字
            console.log(sessionStorage.getItem("age"))
            // 讀取物件
            console.log(sessionStorage.getItem("person"))
            console.log(JSON.parse(sessionStorage.getItem("person")))
        }

        function remove() {
            // 洗掉字串
            sessionStorage.removeItem("name")
            // 移除數字
            sessionStorage.removeItem("age")
            // 移除物件
            sessionStorage.removeItem("person")
        }

        function clearAll() {
            console.log("clear...");
            sessionStorage.clear()
        }
    </script>
</body>
</html>

1.9 組件的自定義事件

1.9.1 使用說明

  1. 一種組件間通信的方式,適用于:子組件 ===> 父組件

  2. 使用場景:A 是父組件,B 是子組件,B 想給 A 傳資料,那么就要在 A 中給 B 系結自定義事件(事件的回呼在 A 中),

  3. 系結自定義事件:

    1. 第一種方式,在父組件中:<Demo @helloWorld="test"/><Demo v-on:helloWorld="test"/>

    2. 第二種方式,在父組件中:

      <Demo ref="demo"/>
      ......
      mounted(){
         this.$refs.xxx.$on('helloWorld', this.test)
      }
      
    3. 若想讓自定義事件只能觸發一次,可以使用 once 修飾符,或 $once 方法,

  4. 觸發自定義事件:this.$emit('helloWorld',資料)

  5. 解綁自定義事件this.$off('helloWorld')

  6. 組件上也可以系結原生 DOM 事件,需要使用 native 修飾符,

  7. 注意:通過 this.$refs.xxx.$on('helloWorld',回呼) 系結自定義事件時,回呼要么配置在methods中要么用箭頭函式,否則 this 指向會出問題!

1.9.2 代碼示例

父組件 App

<template>
  <div id="app" >
    <h1>學校名稱是:{{ schoolName }}</h1>
    <h1>學生姓名是:{{ studentName }}</h1>

    <!-- 通過 props 來實作子組件給父組件傳遞資料 -->
    <School :getSchoolName="getSchoolName" />

    <!-- 第一種寫法:通過父組件給子組件系結一個自定義事件來實作子組件給父組件傳遞資料 使用 @ 或者 v-on -->
    <!-- <Student @getStudentName="getStudentName" /> -->
    
    <!-- 第二種寫法:通過父組件給子組件系結一個自定義事件來實作子組件給父組件傳遞資料 使用 ref-->
    <Student ref="student" />
    
    <!-- 通過父組件給子組件系結一個自定義事件來實作子組件給父組件傳遞資料,只觸發一次 -->
    <!-- <Student @getStudentName.once="getStudentName"/> -->
    <!-- <Student ref="student" /> -->
    
    <!-- 使用組件原生的方法 -->
    <!-- <Student @click.native="show" /> -->
    
    <!-- <Student @getStudentName="getStudentName" @getDemo="getDemo" /> -->
  </div>
</template>

<script>
import School from "./components/School.vue";
import Student from "./components/Student.vue";
export default {
  components: { School, Student },
  data() {
    return {
      schoolName: "",
      studentName: "",
    };
  },

  methods: {
    // 接收 School 子組件傳遞來的資料
    getSchoolName(name) {
      console.log("App 組件收到了學校名稱", name);
      this.schoolName = name;
    },

    // 接收 Student 子組件傳遞來的資料
    getStudentName(name) {
      console.log("App 組件收到了學生姓名", name);
      this.studentName = name;
    },

    // 接收多個資料
    getDemo(...params) {
      console.log(...params);
    },

    show() {
      alert(123)
    }
  },

  mounted() {
    // 寫法一
    this.$refs.student.$on("getStudentName", (name) => {
      // 普通函式寫法 此時 this 是 VueComponent 實體 Student
      // 箭頭函式寫法 此時 this 是 vm 
      console.log(this,"@@@", name);
       this.studentName = name
    })
    // 寫法二
    // this.$refs.student.$on("getStudentName", this.getStudentName)
    // this.$refs.student.$once("getStudentName", this.getStudentName)
  },
};
</script>

<style>
.app {
  background-color: gray;
  padding: 5px;
}
</style>

子組件 School

<template>
  <div >
    <h2>學校名稱: {{ name }}</h2>
    <h2>學校地址: {{ address }}</h2>
    <button @click="sendSchoolName">把學校名稱給 App 組件</button>
  </div>
</template>

<script>
export default {
  name: "School",
  props: ["getSchoolName"],
  data() {
    return {
      name: "北京大學",
      address: "北京",
    };
  },
  methods: {
    sendSchoolName() {
      this.getSchoolName(this.name);
    },
  },
};
</script>

<style>
.school {
  background-color: skyblue;
  padding: 5px;
}
</style>

子組件 Student

<template>
  <div >
    <h2>學生姓名: {{ name }}</h2>
    <h2>學生性別: {{ sex }}</h2>
    <h2>學生年齡: {{ age }}</h2>
    <button @click="sendStudentName">把學生姓名給 App 組件</button>
    <button @click="unbind">解綁自定義事件</button>
    <button @click="death">銷毀當前組件實體</button>
  </div>
</template>

<script>
// 引入混入
export default {
  name: "Student",

  data() {
    return {
      name: "張三",
      sex: "男",
      age: 20,
    };
  },
  methods: {
    sendStudentName() {
      // 觸發 student 組件實體的 getStudentName 事件
      this.$emit("getStudentName", this.name);
      this.$emit("getDemo", 1, 2, 3, 4);
    },
    // 解綁自定義事件
    unbind() {
      // 解綁一個自定義事件
      // this.$off("getStudentName");

      // 解綁多個自定義事件
      this.$off(["getStudentName", "getDemo"]);
    },
    // 銷毀當前組件實體
    death() {
      // 銷毀了當前Student組件的實體,銷毀后所有Student實體的自定義事件全都不奏效,
      this.$destroy()
    }
  },
};
</script>

<style lang="less" scoped>
.student {
  background-color: orange;
  padding: 5px;
  margin-top: 30px;
}
</style>

1.10 全域事件總線

1.10.1 使用說明

  1. 一種組件間通信的方式,適用于任意組件間通信

  2. 安裝全域事件總線:

    new Vue({
    	......
    	beforeCreate() {
    		Vue.prototype.$bus = this //安裝全域事件總線,$bus就是當前應用的vm
    	},
        ......
    }) 
    
  3. 使用事件總線:

    1. 接收資料:A 組件想接收資料,則在 A 組件中給 $bus 系結自定義事件,事件的回呼留在 A 組件自身,

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.$bus.$on('xxxx',this.demo)
      }
      
    2. 提供資料:this.$bus.$emit('xxxx',資料)

  4. 最好在 beforeDestroy 鉤子中,用 $off 去解綁當前組件所用到的事件,

1.10.2 代碼示例

main.js 中安裝全域事件總線

import Vue from 'vue'

import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  el: "#app",
  render: h => h(App),
  beforeCreate() {
    // 安裝全域事件總線
    Vue.prototype.$bus = this
  }
})

在組件 School 中掛載全域事件

<template>
  <div >
    <h2>學校名稱: {{ name }}</h2>
    <h2>學校地址: {{ address }}</h2>
  </div>
</template>

<script>
export default {
  name: "School",
  data() {
    return {
      name: "北大大學",
      address: "北京",
    };
  },
  methods: {},
  // 在組件掛載時系結一個事件
  mounted() {
    this.$bus.$on("getStudentName", (data) => {
      // 此時 this 是 VueComponent 的實體 School
      console.log(this);
      console.log("School 組件收到了資料:", data);
    });
  },
  // 在組件銷毀前解綁事件
  beforeDestroy() {
    this.$bus.$off("getStudentName")
  }
};
</script>

<style>
.demo {
  background-color: skyblue;
}
</style>

Student 組件中觸發全域事件

<template>
  <div >
    <h2 >學生姓名: {{ name }}</h2>
    <h2>學生性別: {{ sex }}</h2>
    <h2>學生年齡: {{ age }}</h2>
    <button @click="sendStudentName">把學生名字給 School 組件</button>
  </div>
</template>

<script>
// 引入混入
export default {
  name: "Student",

  data() {
    return {
      name: "張三",
      sex: "男",
      age: 20,
    };
  },
  methods: {
    sendStudentName() {
      // 觸發事件
      this.$bus.$emit("getStudentName", this.name)
    }
  },
};
</script>

<!-- <style>
  .demo {
    background-color: orange;
  }
</style> -->
<!-- 不指定,默認使用 css -->
<!--  scoped: 表示樣式只對指定的組件起作用-->
<!-- <style scoped>
  .demo {
    background-color: orange;
  }
</style> -->

<!-- lang: 指定用什么樣式  -->
<!-- less 需要引入 less-loader:npm install less-loader 指定版本:npm install less-loader@7 -->
<!-- npm view webpack versions 查看 webpack 版本命令,同理: -->
<style lang="less" scoped>
  .demo {
    background-color: orange;
    // less 與 css 的一個區別就是 less 可以疊加寫,css 不可以
    .title {
      font-size: 40px;
    }
  }
</style>

1.11 訊息訂閱與發布

1.11.1 說明使用

  1. 一種組件間通信的方式,適用于任意組件間通信

  2. 它包含以下操作:

    1. 訂閱訊息--對應系結事件監聽
    2. 發布訊息--分發事件
    3. 取消訊息訂閱--解綁事件監聽
  3. PubSub.js

    1. 在線檔案
    2. 安裝:
    3. 相關語法:
      • import PubSub from 'pubsub-js' : 引入
      • PubSub.subscribe(‘msgName’, functon(msgName, data){}): 訂閱
      • PubSub.publish(‘msgName’,data): 發布訊息,觸發訂閱的回呼函式呼叫
      • PubSub.unsubscribe(token): 取消訊息的訂閱
  4. 使用步驟:

    1. 安裝 pubsubnpm i pubsub-js

    2. 引入: import pubsub from 'pubsub-js'

    3. 接收資料:A組件想接收資料,則在A組件中訂閱訊息,訂閱的回呼留在A組件自身,

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.pid = pubsub.subscribe('xxx',this.demo) //訂閱訊息
      }
      
    4. 提供資料:pubsub.publish('xxx',資料)

    5. 最好在 beforeDestroy 鉤子中,用 PubSub.unsubscribe(pid)取消訂閱,

1.11.2 代碼示例

School 組件訂閱訊息

<template>
  <div >
    <h2>學校名稱: {{ name }}</h2>
    <h2>學校地址: {{ address }}</h2>
  </div>
</template>

<script>
import pubsub from "pubsub-js";
export default {
  name: "School",
  data() {
    return {
      name: "北大大學",
      address: "北京",
    };
  },
  methods: {},
  mounted() {
    // 訂閱訊息
    const pubId = pubsub.subscribe("sendStudentName", (messageName, data) => {
      // 箭頭函式寫法 此時 this 是 VueComponent 實體 School
      console.log(this);
      console.log(messageName, data);
    })
    // pubsub.subscribe("sendStudentName", function (messageName, data) {
    //   // 普通函式寫法,此時 this undefined
    //   console.log(this);
    //   console.log(messageName, data);
    // });
  },
  beforeDestroy() {
    // 取消訂閱訊息
    // 取消訂閱訊息時要用 pubId 去取消訂閱
    pubsub.unsubscribe(this.pubId);
  },
};
</script>

<style>
.demo {
  background-color: skyblue;
}
</style>

Student 組件消費訊息

<template>
  <div >
    <h2 >學生姓名: {{ name }}</h2>
    <h2>學生性別: {{ sex }}</h2>
    <h2>學生年齡: {{ age }}</h2>
    <button @click="sendStudentName">把學生姓名給 School 組件</button>
  </div>
</template>

<script>
// 引入訊息訂閱
import pubsub from "pubsub-js";
export default {
  name: "Student",
  data() {
    return {
      name: "張三",
      sex: "男",
      age: 20,
    };
  },
  methods: {
    sendStudentName() {
      // 發布訊息
      // 第一個引數是訊息名
      pubsub.publish("sendStudentName", this.name);
    },
  },
};
</script>

<!-- <style>
  .demo {
    background-color: orange;
  }
</style> -->
<!-- 不指定,默認使用 css -->
<!--  scoped: 表示樣式只對指定的組件起作用-->
<!-- <style scoped>
  .demo {
    background-color: orange;
  }
</style> -->

<!-- lang: 指定用什么樣式  -->
<!-- less 需要引入 less-loader:npm install less-loader 指定版本:npm install less-loader@7 -->
<!-- npm view webpack versions 查看 webpack 版本命令,同理: -->
<style lang="less" scoped>
.demo {
  background-color: orange;
  // less 與 css 的一個區別就是 less 可以疊加寫,css 不可以
  .title {
    font-size: 40px;
  }
}
</style>

1.12 nextTick

  1. 語法:this.$nextTick(回呼函式)
  2. 作用:在下一次 DOM 更新結束后執行其指定的回呼
  3. 什么時候用:當改變資料后,要基于更新后的新 DOM 進行某些操作時,要在 nextTick 所指定的回呼函式中執行

1.13 過度與影片

1.13.1 使用說明

  1. 作用:在插入、更新或移除 DOM 元素時,在合適的時候給元素添加樣式類名

  2. 寫法:

    1. 準備好樣式:

      • 元素進入的樣式:
        1. v-enter:進入的起點
        2. v-enter-active:進入程序中
        3. v-enter-to:進入的終點
      • 元素離開的樣式:
        1. v-leave:離開的起點
        2. v-leave-active:離開程序中
        3. v-leave-to:離開的終點
    2. 使用<transition>包裹要過度的元素,并配置 name 屬性:

      <transition name="hello">
      	<h1 v-show="isShow">你好啊!</h1>
      </transition>
      
    3. 備注:若有多個元素需要過度,則需要使用:<transition-group>,且每個元素都要指定 key

1.13.2 代碼示例

transition

<template>
  <div>
    <button @click="isShow = !isShow">顯示/隱藏</button>
    <!-- appear 表示頁面一進來就進行影片效果 -->
    <transition name="hello" appear>
      <h1 v-show="isShow">Hello World</h1>
    </transition>
  </div>
</template>

<script>
export default {
  name: "Test1",
  data() {
    return {
      isShow: true,
    };
  },
};
</script>

<style scoped>
h1 {
  background-color: orange;
}

.hello-enter-active {
  animation: helloWorld 0.5s linear;
}

.hello-leave-active {
  animation: helloWorld 0.5s linear reverse;
}

@keyframes helloWorld {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0px);
  }
}
</style>

transition-group

<template>
  <div>
    <button @click="isShow = !isShow">顯示/隱藏</button>
    <!-- appear 表示頁面一進來就進行影片效果 -->
    <!-- transition-group 包裹一組標簽,需要指定 key -->
    <transition-group name="hello" appear="">
      <h1 v-show="isShow" key="1">Hello</h1>
      <h1 v-show="isShow" key="2">World</h1>
    </transition-group>
  </div>
</template>

<script>
export default {
  name: "Test2",
  data() {
    return {
      isShow: true,
    };
  },
};
</script>

<style scoped>
h1 {
  background-color: skyblue;
}

/* 進入的起點,離開的終點 */
.hello-enter,
.hello-leave-to {
  transform: translateX(-100%);
}

.hello-enter-active,
.hello-leave-active {
  transition: 0.5s linear;
}

/* 離開的起點,進入的重點 */
.hello-leave,
.hello-enter-to {
  transform: translateX(0);
}
</style>

使用第三方影片庫 Animate.css

<template>
  <div>
    <button @click="isShow = !isShow">顯示/隱藏</button>
    <!-- 使用第三方影片庫 -->
    <transition-group
      appear
      name="animate__animated animate__bounce"
      enter-active-
      leave-active-
    >
      <h1 v-show="isShow" key="1">Hello</h1>
      <h1 v-show="isShow" key="2">World</h1>
    </transition-group>
  </div>
</template>

<script>
// Animate.css 使用步驟
// 0.官網地址:https://animate.style/
// 1.安裝:npm install animate.css --save
// 2.引入: import "animate.css";

import "animate.css";
export default {
  name: "Test3",
  data() {
    return {
      isShow: true,
    };
  },
};
</script>

<style scoped>
h1 {
  background-color: orange;
}
</style>

1.14 插槽

1.14.1 使用說明

  1. 作用:讓父組件可以向子組件指定位置插入 html 結構,也是一種組件間通信的方式,適用于 父組件 ===> 子組件

  2. 分類:默認插槽、具名插槽、作用域插槽

1.14.2 默認插槽

父組件

<Category>
    <div>html結構1</div>
</Category>

子組件

<template>
	<div>
        <!-- 定義插槽 -->
        <slot>插槽默認內容...</slot>
    </div>
</template>

1.14.3 具名插槽

父組件中

<Category>
    <template slot="center">
        <div>html結構1</div>
    </template>

    <template v-slot:footer>
        <div>html結構2</div>
    </template>
</Category>

子組件中

<template>
	<div>
        <!-- 定義插槽 -->
        <slot name="center">插槽默認內容...</slot>
        <slot name="footer">插槽默認內容...</slot>
    </div>
</template>

1.14.4 作用域插槽

  1. 理解:資料在組件的自身,但根據資料生成的結構需要組件的使用者來決定,games 資料在 Category 組件中,但使用資料所遍歷出來的結構由 App 組件決定)

  2. 具體編碼:

    父組件中

    <Category>
        <template scope="scopeData">
            <!-- 生成的是ul串列 -->
            <ul>
                <li v-for="g in scopeData.games" :key="g">{{g}}</li>
            </ul>
        </template>
    </Category>
    
    <Category>
        <template slot-scope="scopeData">
            <!-- 生成的是h4標題 -->
            <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
        </template>
    </Category>
    

    子組件

    <template>
        <div>
            <slot :games="games"></slot>
        </div>
    </template>
    
    <script>
        export default {
            name:'Category',
            props:['title'],
            //資料在子組件自身
            data() {
                return {
                    games:['紅色警戒','穿越火線','勁舞團','超級瑪麗']
                }
            },
        }
    </script>
    

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523212.html

標籤:其他

上一篇:JavaScript 使用 Notification 發送系統通知

下一篇:在不中斷行程或主執行緒的情況下不斷運行代碼

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • IEEE1588PTP在數字化變電站時鐘同步方面的應用

    IEEE1588ptp在數字化變電站時鐘同步方面的應用 京準電子科技官微——ahjzsz 一、電力系統時間同步基本概況 隨著對IEC 61850標準研究的不斷深入,國內外學者提出基于IEC61850通信標準體系建設數字化變電站的發展思路。數字化變電站與常規變電站的顯著區別在于程序層傳統的電流/電壓互 ......

    uj5u.com 2020-09-10 03:51:52 more
  • HTTP request smuggling CL.TE

    CL.TE 簡介 前端通過Content-Length處理請求,通過反向代理或者負載均衡將請求轉發到后端,后端Transfer-Encoding優先級較高,以TE處理請求造成安全問題。 檢測 發送如下資料包 POST / HTTP/1.1 Host: ac391f7e1e9af821806e890 ......

    uj5u.com 2020-09-10 03:52:11 more
  • 網路滲透資料大全單——漏洞庫篇

    網路滲透資料大全單——漏洞庫篇漏洞庫 NVD ——美國國家漏洞庫 →http://nvd.nist.gov/。 CERT ——美國國家應急回應中心 →https://www.us-cert.gov/ OSVDB ——開源漏洞庫 →http://osvdb.org Bugtraq ——賽門鐵克 →ht ......

    uj5u.com 2020-09-10 03:52:15 more
  • 京準講述NTP時鐘服務器應用及原理

    京準講述NTP時鐘服務器應用及原理京準講述NTP時鐘服務器應用及原理 安徽京準電子科技官微——ahjzsz 北斗授時原理 授時是指接識訓通過某種方式獲得本地時間與北斗標準時間的鐘差,然后調整本地時鐘使時差控制在一定的精度范圍內。 衛星導航系統通常由三部分組成:導航授時衛星、地面檢測校正維護系統和用戶 ......

    uj5u.com 2020-09-10 03:52:25 more
  • 利用北斗衛星系統設計NTP網路時間服務器

    利用北斗衛星系統設計NTP網路時間服務器 利用北斗衛星系統設計NTP網路時間服務器 安徽京準電子科技官微——ahjzsz 概述 NTP網路時間服務器是一款支持NTP和SNTP網路時間同步協議,高精度、大容量、高品質的高科技時鐘產品。 NTP網路時間服務器設備采用冗余架構設計,高精度時鐘直接來源于北斗 ......

    uj5u.com 2020-09-10 03:52:35 more
  • 詳細解讀電力系統各種對時方式

    詳細解讀電力系統各種對時方式 詳細解讀電力系統各種對時方式 安徽京準電子科技官微——ahjzsz,更多資料請添加VX 衛星同步時鐘是我京準公司開發研制的應用衛星授時時技術的標準時間顯示和發送的裝置,該裝置以M國全球定位系統(GLOBAL POSITIONING SYSTEM,縮寫為GPS)或者我國北 ......

    uj5u.com 2020-09-10 03:52:45 more
  • 如何保證外包團隊接入企業內網安全

    不管企業規模的大小,只要企業想省錢,那么企業的某些服務就一定會采用外包的形式,然而看似美好又經濟的策略,其實也有不好的一面。下面我通過安全的角度來聊聊使用外包團的安全隱患問題。 先看看什么服務會使用外包的,最常見的就是話務/客服這種需要大量重復性、無技術性的服務,或者是一些銷售外包、特殊的職能外包等 ......

    uj5u.com 2020-09-10 03:52:57 more
  • PHP漏洞之【整型數字型SQL注入】

    0x01 什么是SQL注入 SQL是一種注入攻擊,通過前端帶入后端資料庫進行惡意的SQL陳述句查詢。 0x02 SQL整型注入原理 SQL注入一般發生在動態網站URL地址里,當然也會發生在其它地發,如登錄框等等也會存在注入,只要是和資料庫打交道的地方都有可能存在。 如這里http://192.168. ......

    uj5u.com 2020-09-10 03:55:40 more
  • [GXYCTF2019]禁止套娃

    git泄露獲取原始碼 使用GET傳參,引數為exp 經過三層過濾執行 第一層過濾偽協議,第二層過濾帶引數的函式,第三層過濾一些函式 preg_replace('/[a-z,_]+\((?R)?\)/', NULL, $_GET['exp'] (?R)參考當前正則運算式,相當于匹配函式里的引數 因此傳遞 ......

    uj5u.com 2020-09-10 03:56:07 more
  • 等保2.0實施流程

    流程 結論 ......

    uj5u.com 2020-09-10 03:56:16 more
最新发布
  • 使用Django Rest framework搭建Blog

    在前面的Blog例子中我們使用的是GraphQL, 雖然GraphQL的使用處于上升趨勢,但是Rest API還是使用的更廣泛一些. 所以還是決定回到傳統的rest api framework上來, Django rest framework的官網上給了一個很好用的QuickStart, 我參考Qu ......

    uj5u.com 2023-04-20 08:17:54 more
  • 記錄-new Date() 我忍你很久了!

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 大家平時在開發的時候有沒被new Date()折磨過?就是它的諸多怪異的設定讓你每每用的時候,都可能不小心踩坑。造成程式意外出錯,卻一下子找不到問題出處,那叫一個煩透了…… 下面,我就列舉它的“四宗罪”及應用思考 可惡的四宗罪 1. Sa ......

    uj5u.com 2023-04-20 08:17:47 more
  • 使用Vue.js實作文字跑馬燈效果

    實作文字跑馬燈效果,首先用到 substring()截取 和 setInterval計時器 clearInterval()清除計時器 效果如下: 實作代碼如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta ......

    uj5u.com 2023-04-20 08:12:31 more
  • JavaScript 運算子

    JavaScript 運算子/運算子 在 JavaScript 中,有一些運算子可以使代碼更簡潔、易讀和高效。以下是一些常見的運算子: 1、可選鏈運算子(optional chaining operator) ?.是可選鏈運算子(optional chaining operator)。?. 可選鏈操 ......

    uj5u.com 2023-04-20 08:02:25 more
  • CSS—相對單位rem

    一、概述 rem是一個相對長度單位,它的單位長度取決于根標簽html的字體尺寸。rem即root em的意思,中文翻譯為根em。瀏覽器的文本尺寸一般默認為16px,即默認情況下: 1rem = 16px rem布局原理:根據CSS媒體查詢功能,更改根標簽的字體尺寸,實作rem單位隨螢屏尺寸的變化,如 ......

    uj5u.com 2023-04-20 08:02:21 more
  • 我的第一個NPM包:panghu-planebattle-esm(胖虎飛機大戰)使用說明

    好家伙,我的包終于開發完啦 歡迎使用胖虎的飛機大戰包!! 為你的主頁添加色彩 這是一個有趣的網頁小游戲包,使用canvas和js開發 使用ES6模塊化開發 效果圖如下: (覺得圖片太sb的可以自己改) 代碼已開源!! Git: https://gitee.com/tang-and-han-dynas ......

    uj5u.com 2023-04-20 08:01:50 more
  • 如何在 vue3 中使用 jsx/tsx?

    我們都知道,通常情況下我們使用 vue 大多都是用的 SFC(Signle File Component)單檔案組件模式,即一個組件就是一個檔案,但其實 Vue 也是支持使用 JSX 來撰寫組件的。這里不討論 SFC 和 JSX 的好壞,這個仁者見仁智者見智。本篇文章旨在帶領大家快速了解和使用 Vu ......

    uj5u.com 2023-04-20 08:01:37 more
  • 【Vue2.x原始碼系列06】計算屬性computed原理

    本章目標:計算屬性是如何實作的?計算屬性快取原理以及洋蔥模型的應用?在初始化Vue實體時,我們會給每個計算屬性都創建一個對應watcher,我們稱之為計算屬性watcher ......

    uj5u.com 2023-04-20 08:01:31 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:01:10 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:00:32 more