<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>插槽指令</title> <style> body { font-size: 30px; } li:hover { color: orange; cursor: pointer; } .del:hover { color: red; } </style> </head> <body> <div id="app"> <p> <input type="text" v-model="info"> <button @click="add_msg">留言</button> <ul> <msg-tag :msg="msg" v-for="(msg, i) in msgs" :key="msg"> <!--template经过v-slot绑定子组件内部slot插槽标签的name属性值--> <template v-slot:del_btn> <span @click="del_fn(i)" class="del">x</span> </template> </msg-tag> </ul> </p> </div> </body> <script src="js/vue.js"></script> <script> let msgTag = { props: ['msg'], template: ` <li> <!--slot标签是在子组件中占位,父组件模板中能够经过name名字来填充--> <slot name="del_btn"></slot> <span>{{ msg }}</span> </li> `, }; new Vue({ el: '#app', components: { msgTag }, data: { info: '', msgs: JSON.parse(sessionStorage.msgs || '[]'), }, methods: { add_msg() { let info = this.info; if (info) { this.msgs.unshift(this.info); this.info = ''; sessionStorage.msgs = JSON.stringify(this.msgs); } }, del_fn(index) { console.log(index); this.msgs.splice(index, 1); sessionStorage.msgs = JSON.stringify(this.msgs); } } }); </script> </html>
环境css
1)安装node:官网下载安装包,傻瓜式安装:https://nodejs.org/zh-cn/ 2)安装cnpm >:npm install -g cnpm --registry=https://registry.npm.taobao.org 3)安装脚手架 >:cnpm install -g @vue/cli 4)清空缓存处理(若是第二、3补出问题能够执行该条命令) >:npm cache clean --force
建立项目html
项目目录介绍vue
|vue-proj | |node_modules 项目依赖 | |public | | | 图标、单页面.html | |src | | |assets 静态文件(img、css、js) | | |components 小组件 | | |views 页面组件 | | |App.vue 根组件 | | |main.js 主脚本文件 | | |router.js 安装vue-router插件的脚本文件 - 配置路由的 | | |store.js 安装vuex插件的脚本文件 - 全局仓库 - 数据共享 | |配置文件们 | |README.md 关键命令说明
main.jsnode
// import 别名 from '文件(后缀能够省略)' import Vue from 'vue' // import App from './App.vue' import App from './App' // 导入时能够省略后缀 import router from './router' // .表明相对路径的当前路径 import store from '@/store.js' // @表示src绝对路径 Vue.config.productionTip = false; // new Vue({ // router, // store, // render: h => h(App) // }).$mount('#app'); new Vue({ el: '#app', router: router, store, // render: (fn) => { // return fn(App) // } render (fn) { // 读取组件渲染给挂载点el return fn(App) } });
组件 .vue 文件:模板(template) + 脚本(scpirt) + 样式(style)vue-router
<template> <!--组件有且只有一个根标签--> <div id="app"> <h1 @click="btnClick">{{ title }}</h1> </div> </template> <script> // 组件内部导出,其它文件才能import导入该组件 export default { name: "App", data() { return { title: '主页' } }, methods: { btnClick() { console.log(this.title) } } } </script> <!--scoped样式组件局部化--> <style scoped> h1 { color: red; } </style>