# √vue

# √vue插槽

在v2.6中,为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。它取代了 slot 和 slot-scope 。

  • 父组件
<template>
  <div class="about">
    <h1>This is an about page</h1>
    <H>
      插槽
	 <!-- 具名插槽老式写法 -->
     <!-- <div slot='ff'>插槽fff</div> -->
      <!-- <template v-slot:header>
        <h1>Here might be a page title</h1>
      </template> -->
      <!-- <div slot='header'>9999</div> -->
      <template #header>
        <h1>Here might be a page title!!!</h1>
      </template>

       <template v-slot:king="slotProps">
      {{ slotProps.userName }}---√
      </template>
    </H>
  </div>
</template>
<script>
import H from "@/components/HelloWorld"
export default {
  components:{
    H
  }
}
</script>
  • 子组件
<template>
  <div>
   aaaaaaa
  <slot>slot1</slot>
   bbbbbbbbbb
  <slot name="ff">slotffff</slot>
   cccccccccc
  <slot name='header'>header</slot>
  <slot name='king' :userName='userName'></slot>
  </div>
</template>
<script>
export default {
  data(){
    return{
      userName:"myusername"
    }
  }
}
</script>
  • 新旧插槽写法
<!-- old -->
<children>
  <template slot="header">
    <h1>Here might be a page title</h1>
  </template>
  <template slot="default">
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </template>
</children>

<!-- new -->
<children>
  <template v-slot:header>
  <!--  <template #header> 具名插槽可缩写形式 -->
    <h1>Here might be a page title</h1>
  </template>
  <template v-slot:default>
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </template>
</children>
<!-- old -->
<children>
  <template slot="default" slot-scope="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</children>

<!-- new -->
<children>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</children>
  • 新版具名插槽在template上写v-slot指令
  • 具名插槽可缩写形式:#XXX

# √v-model

  • 在组件上使用v-model:改造course-add为支持v-model的版本
<!-- 自定义组件支持v-model需要实现内部input的:value和@input -->
<course-add v-model="course" @add-course="addCourse"></course-add>
<script>
	Vue.component('course-add', { 
		// 接收父组件传递value,不需要额外维护
		course props: ['value'], 
		template: ` 
		<div>
		<!-- 需要实现input的:value和@input --> 
		<input :value="value" @input="onInput" @keydown.enter="addCourse"/> 
		<button v-on:click="addCourse">新增课程</button> </div> `,
		methods: {
			addCourse() { 
				// 派发事件不再需要传递数据
				this.$emit('add-course') 
		  },onInput(e) {
			  this.$emit('input', e.target.value)
		  } 
		}, 
	})
	
	const app = new Vue({ 
		data: { 
			course: '', 
			// 还原course 
		},
		methods: { 
			addCourse() {
				// 还原addCourse 
				this.courses.push(this.course); 
				this.course = ''; 
				} 
			} 
	  }) 
</script>

v-model默认转换是:value和@input,如果想要修改这个行为,可以通过定义model选项

Vue.component('course-add', { model: { prop: 'value', event: 'change' } })
最后更新: 2/22/2022, 8:38:03 AM