[TOC]
>[success] # toRef 以及 context 參數
這章講解一下 **2** 個新的知識點,一個是 **composition API** 中的 **toRef** API,另一個是我們之前講過的 **setup 函數** 的 **第2個參數 context** 。
>[success] ## toRef
1. **解構賦值響應式數據正確寫法**
我們之前通過 **toRefs** 來解決 **解構賦值數據響應式問題** ,代碼如下:
**index.html**
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>toRef</title>
<!-- 通過cdn方式引入vue -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// toRef
const app = Vue.createApp({
template: `
<div>{{name}}</div>
`,
/**
* created 實例被完全初始化之前
* @param {object} props - 當前組件的props
* @param {number} contex - 上下文
*/
setup(props, contex) {
const { reactive, toRefs } = Vue
const data = reactive({ name: 'dell' })
// 解構賦值
const { name } = toRefs(data)
// 2s 后修改name變量
setTimeout(() => {
name.value = 'lee'
}, 2000)
return { name }
}
})
const vm = app.mount('#root')
</script>
</html>
~~~
2. **解構賦值響應式數據錯誤寫法**
如果在 **解構賦值時** ,我們把 **name** 改成 **age** ,這時候我們就會發現,在一開始 **data** 中沒有 **age** , 這時候 **解構賦值時有 age ,就會發生錯誤** ,這是 **因為 toRefs 這種語法,它從 data 這樣一個響應式對象里去找數據時,如果找不到,它不會給 age 一個默認的響應式的引用,而是給 age 賦值為 undefined,這樣的話, age 最開始不存在 data 中,它后面就不具備響應式,再改它,也無效果** ,代碼如下:
**index.html**
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>toRef</title>
<!-- 通過cdn方式引入vue -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// toRef
const app = Vue.createApp({
template: `
<div>{{age}}</div>
`,
/**
* created 實例被完全初始化之前
* @param {object} props - 當前組件的props
* @param {number} contex - 上下文
*/
setup(props, contex) {
const { reactive, toRefs } = Vue
const data = reactive({ name: 'dell' })
// 解構賦值
const { age } = toRefs(data)
// 2s 后修改name變量
setTimeout(() => {
age.value = 'lee'
}, 2000)
return { age }
}
})
const vm = app.mount('#root')
</script>
</html>
~~~
3. **toRef**
如果想解決上面的問題,我們可以用 **toRef** ,代碼如下:
**index.html**
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>toRef</title>
<!-- 通過cdn方式引入vue -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// toRef
const app = Vue.createApp({
template: `
<div>{{age}}</div>
`,
/**
* created 實例被完全初始化之前
* @param {object} props - 當前組件的props
* @param {number} contex - 上下文
*/
setup(props, contex) {
const { reactive, toRef } = Vue
const data = reactive({ name: 'dell' })
// 意思是從 data 中取 age ,如果能取到就用取到的值,
// 取不到就聲明一個空的響應式數據
const age = toRef(data, 'age')
// 2s 后給 age 賦值
setTimeout(() => {
age.value = 'lee'
}, 2000)
// 導出 age ,這里必須是對象的形式,就像在 vue2.x 時 return {} 一樣
return { age }
}
})
const vm = app.mount('#root')
</script>
</html>
~~~
**建議一般情況不要用 toRef** ,一般來說,如果后面代碼中要用到 **age** ,不妨直接在 **data** 中提前定義一個空的 **age** ,代碼如下:
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>toRef</title>
<!-- 通過cdn方式引入vue -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// toRef
const app = Vue.createApp({
template: `
<div>{{age}}</div>
`,
/**
* created 實例被完全初始化之前
* @param {object} props - 當前組件的props
* @param {number} contex - 上下文
*/
setup(props, contex) {
const { reactive, toRefs } = Vue
const data = reactive({ name: 'dell', age: '' })
// 2s 后給 age 賦值
setTimeout(() => {
data.age = 'lee'
}, 2000)
// 解構賦值
const { age } = toRefs(data)
// 導出 age ,這里必須是對象的形式,就像在 vue2.x 時 return {} 一樣
return { age }
}
})
const vm = app.mount('#root')
</script>
</html>
~~~
>[success] ## Setup 的第二個參數 context
接下來我們講一下 **context** , **context** 是個 **對象**, 它有 **3** 個 **屬性值**
1. **attrs**
**context** 的第 **1** 個參數是 **attrs(None-Props屬性)** ,下面用它寫一個小例子:
**index.html**
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Setup 的第二個參數 context </title>
<!-- 通過cdn方式引入vue -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// 父組件
const app = Vue.createApp({
template: `<child style="color:red" />`
})
// 子組件
app.component('child', {
/**
* created 實例被完全初始化之前
* @param {object} props - 當前組件的props
* @param {number} contex - 上下文
*/
setup(props, contex) {
// 引入h函數
const { h } = Vue
const { attrs, slots, emit } = contex
// 使用render函數,并且使用 attrs
return () => {
return h('div', {
style: attrs.style
}, 'child')
}
}
})
const vm = app.mount('#root')
</script>
</html>
~~~
2. **slots**
**context** 的第 **2** 個參數是 **slots** , **slots** 是 **父組件傳遞過來的插槽** ,在 **vue2.x** 版本中,我們使用 **slots** 都需要 **this.$slots** ,在新版 **composition API** 中可以使用 **slots** ,例子如下:
**index.html**
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Setup 的第二個參數 context </title>
<!-- 通過cdn方式引入vue -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// 父組件
const app = Vue.createApp({
template: `<child>parent</child>`
})
// 子組件
app.component('child', {
/**
* created 實例被完全初始化之前
* @param {object} props - 當前組件的props
* @param {number} contex - 上下文
*/
setup(props, contex) {
// 引入h函數
const { h } = Vue
const { attrs, slots, emit } = contex
// 使用render函數,并且使用 slots
return () => {
return h('div', {}, slots.default())
}
}
})
const vm = app.mount('#root')
</script>
</html>
~~~
3. **emit**
在舊版 **vue2.x** 版本中, **子組件** 給 **父組件傳值** 通過 **this.$emit** ,代碼如下:
**index.html**
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Setup 的第二個參數 context </title>
<!-- 通過cdn方式引入vue -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// 父組件
const app = Vue.createApp({
template: `<child @change="handleChange">parent</child>`,
methods: {
handleChange(){
alert('handleChange')
}
}
})
// 子組件
app.component('child', {
template: '<div @click="handleClick">123123</div>',
methods: {
handleClick(){
this.$emit('change')
}
}
})
const vm = app.mount('#root')
</script>
</html>
~~~
在新版 **composition API** 中這樣寫即可,代碼如下:
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Setup 的第二個參數 context </title>
<!-- 通過cdn方式引入vue -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// 父組件
const app = Vue.createApp({
methods: {
handleChange(){
alert('handleChange')
}
},
template: `<child @change="handleChange">parent</child>`
})
// 子組件
app.component('child', {
template: '<div @click="handleClick">123123</div>',
/**
* created 實例被完全初始化之前
* @param {object} props - 當前組件的props
* @param {number} contex - 上下文
*/
setup(props, contex) {
const { attrs, slots, emit } = contex
// 定義方法
function handleClick(){
emit('change')
}
// 導出方法
return { handleClick }
}
})
const vm = app.mount('#root')
</script>
</html>
~~~
- vue 26課
- Vue-cli3.0項目搭建
- Vue-ui 創建cli3.0項目
- Vue-ui 界面詳解
- 項目目錄詳解
- public文件夾
- favicon.ico
- index.html
- src文件夾
- api文件夾
- assets文件夾
- components文件夾
- config文件夾
- directive文件夾
- lib文件夾
- mock文件夾
- mock簡明文檔
- router文件夾
- store文件夾
- views文件夾
- App.vue
- main.js
- .browserslistrc
- .editorconfig
- .eslintrc.js
- .gitignore
- babel.config.js
- package-lock.json
- package.json
- postcss.config.js
- README.en.md
- README.md
- vue.config.js
- Vue Router
- 路由詳解(一)----基礎篇
- 路由詳解(二)----進階篇
- Vuex
- Bus
- Vuex-基礎-state&getter
- Vuex-基礎-mutation&action/module
- Vuex-進階
- Ajax請求
- 解決跨域問題
- 封裝axios
- Mock.js模擬Ajax響應
- 組件封裝
- 從數字漸變組件談第三方JS庫使用
- 從SplitPane組件談Vue中如何【操作】DOM
- 渲染函數和JSX快速掌握
- 遞歸組件的使用
- 登陸/登出以及JWT認證
- 響應式布局
- 可收縮多級菜單的實現
- vue雜項
- vue遞歸組件
- vue-cli3.0多環境打包配置
- Vue+Canvas實現圖片剪切
- vue3系統入門與項目實戰
- Vue語法初探
- 初學編寫 HelloWorld 和 Counter
- 編寫字符串反轉和內容隱藏功能
- 編寫TodoList功能了解循環與雙向綁定
- 組件概念初探,對 TodoList 進行組件代碼拆分
- Vue基礎語法
- Vue 中應用和組件的基礎概念
- 理解 Vue 中的生命周期函數
- 常用模版語法講解
- 數據,方法,計算屬性和偵聽器
- 樣式綁定語法
- 條件渲染
- 列表循環渲染
- 事件綁定
- 表單中雙向綁定指令的使用
- 探索組件的理念
- 組件的定義及復用性,局部組件和全局組件
- 組件間傳值及傳值校驗
- 單向數據流的理解
- Non-Props 屬性是什么
- 父子組件間如何通過事件進行通信
- 組件間雙向綁定高級內容
- 使用匿名插槽和具名插槽解決組件內容傳遞問題
- 作用域插槽
- 動態組件和異步組件
- 基礎語法知識點查缺補漏
- Vue 中的動畫
- 使用 Vue 實現基礎的 CSS 過渡與動畫效果
- 使用 transition 標簽實現單元素組件的過渡和動畫效果
- 組件和元素切換動畫的實現
- 列表動畫
- 狀態動畫
- Vue 中的高級語法
- Mixin 混入的基礎語法
- 開發實現 Vue 中的自定義指令
- Teleport 傳送門功能
- 更加底層的 render 函數
- 插件的定義和使用
- 數據校驗插件開發實例
- Composition API
- Setup 函數的使用
- ref,reactive 響應式引用的用法和原理
- toRef 以及 context 參數
- 使用 Composition API 開發TodoList
- computed方法生成計算屬性
- watch 和 watchEffect 的使用和差異性
- 生命周期函數的新寫法
- Provide,Inject,模版 Ref 的用法
- Vue 項目開發配套工具講解
- VueCLI 的使用和單文件組件
- 使用單文件組件編寫 TodoList
- Vue-Router 路由的理解和使用
- VueX 的語法詳解
- CompositionAPI 中如何使用 VueX
- 使用 axios 發送ajax 請求
- Vue3.0(正式版) + TS
- 你好 Typescript: 進入類型的世界
- 什么是 Typescript
- 為什么要學習 Typescript
- 安裝 Typescript
- 原始數據類型和 Any 類型
- 數組和元組
- Interface- 接口初探
- 函數
- 類型推論 聯合類型和 類型斷言
- class - 類 初次見面
- 類和接口 - 完美搭檔
- 枚舉(Enum)
- 泛型(Generics) 第一部分
- 泛型(Generics) 第二部分 - 約束泛型
- 泛型第三部分 - 泛型在類和接口中的使用
- 類型別名,字面量 和 交叉類型
- 聲明文件
- 內置類型
- 總結