Vue学习笔记3(vscode插件, slot插槽)

本文介绍了在Vue开发中如何配置VSCode以实现自动保存和格式化代码,详细讲解了Vue插槽的概念,包括默认插槽、具名插槽、作用域插槽以及v-slot和slot属性的区别,旨在帮助开发者更好地理解和使用Vue的插槽功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. vscode配置(自动保存并格式化代码)

  • .vscode 文件夹
    • 只针对当前项目
    • settings.json:工作空间设置、代码格式化配置、插件配置
  • settings.json
{
	"[vue]": {
		// Defines a default formatter which takes precedence over all other formatter settings. Must be the identifier of an extension contributing a formatter.
		"editor.defaultFormatter": "octref.vetur"
	},
	"[javascript]": {
		// Language Features for TypeScript and JavaScript files
		"editor.defaultFormatter": "vscode.typescript-language-features"
	},
	// https://thesoreon.com/blog/how-to-set-up-eslint-with-typescript-in-vs-code
	"eslint.validate": ["javascript", "javascriptreact"],
	// https://vuejs.github.io/vetur/formatting.html#formatters
	"vetur.format.defaultFormatter.js": "vscode-typescript",
	"vetur.format.defaultFormatter.html": "js-beautify-html",
	"vetur.format.defaultFormatterOptions": {
		"js-beautify-html": {
			"wrap_attributes": "force-expand-multiline"
		}
	},
	//为了符合eslint的两个空格间隔原则
	"editor.tabSize": 2,
	// Error Checking
	"vetur.validation.template": false,
	// Configure glob patterns for excluding files and folders.
	"files.exclude": {
		"node_modules": true
	},
	// Ignores the warning when there are too many changes in a repository.
	"git.ignoreLimitWarning": true,
	// Code action kinds to be run on save.
	"editor.codeActionsOnSave": {
		"source.fixAll.eslint": true
	},
	"git.confirmSync": false,
	// Report errors only , Suppress report warning
	"eslint.quiet": true,
	// Defines space handling before function argument parentheses.
	"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
	"typescript.format.insertSpaceAfterConstructor": true,
	"typescript.format.insertSpaceBeforeFunctionParenthesis": true,
	// Preferred quote style to use for quick fixes: `single` quotes, `double` quotes, or `auto` infer quote type from existing imports. Requires using TypeScript 2.9 or newer in the workspace.
	"javascript.preferences.quoteStyle": "single",
	"javascript.format.insertSpaceAfterConstructor": true,
	"typescript.preferences.quoteStyle": "single",
	// Wrap attributes.
	//  - auto: Wrap attributes only when line length is exceeded.
	//  - force: Wrap each attribute except first.
	//  - force-aligned: Wrap each attribute except first and keep aligned.
	//  - force-expand-multiline: Wrap each attribute.
	//  - aligned-multiple: Wrap when line length is exceeded, align attributes vertically.
	//  - preserve: Preserve wrapping of attributes
	//  - preserve-aligned: Preserve wrapping of attributes but align.
	"html.format.wrapAttributes": "force-expand-multiline",
	// Format a file on save. A formatter must be available, the file must not be saved after delay, and the editor must not be shutting down.
	"editor.formatOnSave": true,
	// Whether or not to indent the code inside <script> and <style> tags in Vue files.
	"prettier.vueIndentScriptAndStyle": false,
	"prettier.singleQuote": true,
	"prettier.useTabs": true
}

2. vue插槽

2.1 插槽内容
  • 内容分发
  • 编译作用域:父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的
  • 默认值
<!-- 父 -->
<navigation-link url="/see">
  {{text}}
</navigation-link>
<navigation-link url="/default">
</navigation-link>
<!-- 子 -->
<template>
  <a
    :href="url"
    class="nav-link"
  >
    <slot>默认内容</slot>
  </a>
</template>
<script>
export default {
  props: ['url']
}
</script>
2.2 具名插槽
  • slot 元素的 name 属性 (子)
  • v-slot 指令 (父),简写 #
  • v-slot 几乎只能添加在 template 标签上
<!-- parent -->
<base-layout>
 <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template #footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>
<!-- child -->
<template>
  <div class="container">
    <div class="d1">
      <slot name="header"></slot>
      <slot></slot>
      <slot name="footer"></slot>
    </div>
    <div class="d2">
      <CustomHeader>
        <slot name="header"></slot>
      </CustomHeader>
      <main>
        <slot></slot>
      </main>
      <footer>
        <slot name="footer"></slot>
      </footer>
    </div>
  </div>
</template>
<script>
import CustomHeader from './header'
export default {
  components: {
    CustomHeader
  }
}
</script>
<style scoped>
.d1 {
  background: red;
}
.d2 {
  background: green;
}
</style>
2.3 作用域插槽
  • 插槽内容能够访问子组件数据
  • 插槽 prop : 绑定在 元素上的 attribute
  • 解构插槽 Prop
  • 动态插槽名
<container title="作用域插槽">
   <current-user>
     <template v-slot:default="slotProps">
       {{ slotProps.user.firstName }}
     </template>
   </current-user>
   <current-user>222</current-user>
   <current-user></current-user>
   <current-user v-slot="slotProps">
     独占默认插槽的缩写语法:{{ slotProps.user.firstName }}
   </current-user>
   <current-user>
     <template v-slot:default="slotProps">
       {{ slotProps.user.firstName }} /
     </template>
     <template v-slot:other="{ other }">
       {{other}}
     </template>
     <template #[dynamicSlotName]></template>
   </current-user>
 </container>


<template>
  <div>
    <slot :user="user">{{ user.lastName }}</slot>
    <slot
      name="other"
      :other="other"
    >i am other default</slot>
  </div>
</template>
<script>
export default {
  data () {
    return {
      user: {
        lastName: 'jack',
        firstName: 'son'
      },
      other: 'i am other'
    }
  }
}
</script>
2.4 其它示例
  • 插槽 prop 允许我们将插槽转换为可复用的模板
  • 可设计封装数据逻辑同时允许父级组件自定义部分布局的可复用组件
<container title="其它示例">
  <todo-list :todos="todos">
    <template #todo="{ todo }">
      <span v-if="todo.isComplete"></span>
      {{ todo.text }}
    </template>
  </todo-list>
  <todo-list :todos="todos"></todo-list>
</container>


<template>
  <ul>
    <li
      v-for="(todo,index) in todos"
      :key="index"
    >
      <!--
    我们为每个 todo 准备了一个插槽,
    将 `todo` 对象作为一个插槽的 prop 传入。
    -->
      <slot
        name="todo"
        :todo="todo"
      >
        <!-- 后备内容 -->
        {{ todo.text }}
      </slot>
    </li>
  </ul>
</template>
<script>
export default {
  props: ['todos']
}
</script>

3. v-slot 和 slot 属性 区别

<template>
  <div>
    <container title="Default slot with text">
      <!-- old -->
      <foo>
        <template slot-scope="{ msg }">
          old1 : {{ msg }}
        </template>
      </foo>

      <!-- new -->
      <foo v-slot="{ msg }">
        new : {{ msg }}
      </foo>

      <!-- 有问题 -->
      <!-- <foo slot-scope="{ msg }">
        old2 : {{ msg }}
      </foo> -->
    </container>
    <container title="Nested default slots">
      <!-- old -->
      <foo>
        <bar slot-scope="foo">
          <baz slot-scope="bar">
            <template slot-scope="baz">
              {{ foo }} {{ bar }} {{ baz }}
            </template>
          </baz>
        </bar>
      </foo>

      <!-- new -->
      <foo v-slot="foo">
        <bar v-slot="bar">
          <baz v-slot="baz">
            {{ foo }} {{ bar }} {{ baz }}
          </baz>
        </bar>
      </foo>
    </container>
    <container title="Named slots">
      <!-- old -->
      <foo>
        <template
          slot="one"
          slot-scope="{ msg }"
        >
          text slot: {{ msg }}
        </template>

        <div
          slot="two"
          slot-scope="{ msg }"
        >
          element slot: {{ msg }}
        </div>
      </foo>

      <!-- new -->
      <foo>
        <template v-slot:one="{ msg }">
          text slot: {{ msg }}
        </template>

        <template v-slot:two="{ msg }">
          <div>
            element slot: {{ msg }}
          </div>
        </template>
      </foo>
    </container>
  </div>
</template>
<script>
import foo from './foo'
import bar from './bar'
import baz from './baz'
import container from '../container'
export default {
  components: {
    foo,
    bar,
    baz,
    container
  }
}
</script>
  • foo/baz/bar
<template>
  <div>i am foo
    <slot :msg="msg"></slot>
    <slot
      name="one"
      :msg="{msg: 1}"
    ></slot>
    <slot
      name="two"
      :msg="{msg: 2}"
    ></slot>
  </div>
</template>
<script>
export default {
  data () {
    return {
      msg: 'foo'
    }
  }
}
</script>


<template>
  <div>i am bar
    <slot :msg="msg"></slot>
  </div>
</template>
<script>
export default {
  data () {
    return {
      msg: 'bar'
    }
  }
}
</script>


<template>
  <div>i am baz
    <slot :msg="msg"></slot>
  </div>
</template>
<script>
export default {
  data () {
    return {
      msg: 'baz'
    }
  }
}
</script>
  • 效果图
    在这里插入图片描述

4. 代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值