Vue04

一.父子组件的访问方式

Vue学习第四天转存失败重新上传取消Vue学习第四天

通常使用$children来获取所有子组件,返回的是子组件对象数组,通过$children[index]返回某一个子组件。不过很少使用

常使用$refs来获取子组件对象 有ref标记的才会被获取

<cpn></cpn>

<cpn ref="second"></cpn>

<cpn ref="third"></cpn>

<button @click="clickBtn">获取子组件的值</button>

<button @click="getRefs">获取带有ref的子组件</button>

methods : {

clickBtn(){

console.log(this.$children[0].number1);

},

getRefs(){

console.log(this.$refs);

}

},

二.子组件访问父组件(不建议使用)

同上,可以使用$parent获取父组件

访问根组件$root

三.使用slot,为了组件更好的复用

1.插槽的基本使用<slot></slot>

2.插槽的默认值<slot><button>按钮</button></slot>

3.如果有多个值,同时放到组件进行替换时,一起作为替换元素

4.具名插槽

<div id="app">

<cpn>

<button slot="first">按钮替换slot</button>

</cpn>

</div>

<template id="cpn">

<div>

<h2>h2标题</h2>

<slot name="first"></slot>

<slot><button>slot默认button</button></slot>

</div>

</template>

5.作用域插槽

父组件替换插槽的标签,但是内容由子组件来提供

slot-scope -> 最新推荐使用v-slot

( 在 2.6.0 中,我们为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。它取代了 slot 和 slot-scope 这两个目前已被废弃但未被移除且仍在文档中的 attribute。)

我理解大致的意思是:template标签中引用了子组件的data数据,slot标签把它包起来,让其中的内容为默认值,此时我父组件想修改这个默认的模板,需要引用子组件中的值,此时我们应该使用这种方法,修改的模板必须用template标签

这里的slotData拿到的是一个对象,所以说可以绑定多个data数据,

如:data="a,b" -> 之后的slotData {"a":["a"] ,"b":["b"]}

这里我们拿到的是{ "data": [ "Java", "Python", "C", "C++", "C#" ] }

<cpn></cpn>

<cpn>

<template v-slot="slotData">

<span v-for="d in slotData.data">{{d}}-</span>

<p></p>

<span>{{slotData.data.join("-")}}</span>

</template>

</cpn>

<template id="cpn">

<div>

<slot :data="pLanguage">

<ul>

<li v-for="l in pLanguage">{{l}}</li>

</ul>

</slot>

</div>

</template>

四.模块化核心:导入和导出

<script type="module" src="test1.js"></script>

<script type="module" src="test2.js"></script>

<script type="module" src="test3.js"></script>

<script type="module" src="test4.js"></script>

设置type属性为module,才能使用import,export

test1.js

export {name,age,sum}       ES6增强写法 本质name:name

test2.js

import {name,age,sum} from "./test1.js";

const defaultObj = {

name,age,multiple

}

export default {defaultObj}

test3.js

import obj from "./test2.js"

console.log(obj.defaultObj.age);

export {num1,num2,num3,num4,num5,num6}

test4.js

import * as info from "./test3.js"

console.log(info.num1)

相关文章: