SpringBoot
微服务阶段
JavaSE:OOP
Mysql:持久化
html+css+js+jquery+框架:视图,框架不熟练,css
javaweb:独立开发MVC三层架构的网站:原始
ssm:框架:简化了我们的开发流程,配置也开始比较复杂
war:tomcat运行
Spring再简化:SpringBoot-jar:内嵌tomcat;微服务架构
服务越来越多:SpringCloud管理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FfzI5I76-1605599028804)(C:\Users\zcq17\AppData\Roaming\Typora\typora-user-images\image-20200915155352692.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a6zn6SNw-1605599028805)(C:\Users\zcq17\AppData\Roaming\Typora\typora-user-images\image-20200915163124099.png)]
第一个SpringBoot项目
- jdk1.8
- maven 3.6.1
- SpringBoot:最新版
- Idea
官方:提供了一个快速生成的网站!Idea集成了这个网站
原理初探
自动配置:
pom.xml
- spring-boot-dependencies:核心依赖在父工程中!
- 我们在写或者引入一些SpringBoot项目的时候,不需要指定版本,就因为有这些版本仓库
启动器:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 启动器:说白了就是SpringBoot的启动场景
- 比如spring-boot-starter-web,他就会帮我们自动导入web环境所有的依赖!
- springboot会将所有的功能场景,都变成一个个的启动器,如果我们要使用什么功能,就只需要找到对应的启动器
主程序
package com.zhou;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author zcq17
* SpringBootApplication:标注这是一个springboot的应用
*/
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
// 将springboot启动
SpringApplication.run(DemoApplication.class, args);
}
}
-
注解
-
@SpringBootConfiguration: springboot配置 @Configuration: spring配置类 @Component :说明这是一个spring的组件 @EnableAutoConfiguration :自动配置 @AutoConfigurationPackage: 自动配置包 @Import(AutoConfigurationPackages.Registrar.class):自动配置包注册 @Import(AutoConfigurationImportSelector.class):自动配置导入选择 //获取所有的包 List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
-
获取候选的配置
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
META-INF/spring.factories: 自动配置的核心文件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZzZP7yp8-1605599028806)(C:\Users\zcq17\AppData\Roaming\Typora\typora-user-images\image-20200915175913845.png)]
结论:springboot所有的自动装配都是在启动的时候扫描并加载的:spring.factories所有的自动装配类都在这里面,但是并不一定生效,要判断条件是否成立,只要导入对应的start,就有对应的启动器了,有了启动器,我们的自动装配才会生效,然后配置成功。
- springboot在启动的时候,从类路径下/META-INF/spring.factories获取指定的值;
- 将自动配置的类导入容器,自动配置就会生效,帮我进行自动配置
- 以前我们需要自动装配的东西,现在springboot帮我做了
- 整合javaEE,解决方案和自动装配的东西都在spring-boot-autoconfigure-2.2.0.RELEASE.jar这个包下
- 它会把所有需要导入的组件,以类名的方式返回,这些组件就会添加到容器
- 容器中也会存在非常多的xxxAutoconfigure的文件(@Bean),就是这些类给容器中导入了这个场景所需要的的所有的组件,并自动配置,@Configuration,Javaconfig!
- 有了自动配置类,免去了我们手动编写配置文件的工作
JSR303校验
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1h0qXh2u-1605599028808)(C:\Users\zcq17\AppData\Roaming\Typora\typora-user-images\image-20200915224711009.png)]
server:
port: 8080
spring:
profiles:
active: dev
---
server:
port: 8082
spring:
profiles: test
---
server:
port: 8083
spring:
profiles: dev
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dpgyFTzl-1605599028810)(C:\Users\zcq17\AppData\Roaming\Typora\typora-user-images\image-20200915233301895.png)]
SpringBoot Web开发
jar:webapp!
自动装配
springboot到底帮我配置了什么,能不能进行修改?能修改哪些东西能不能拓展?
- xxxAutoconfiguration向容器中自动配置组件
- xxxProperties:自动配置类装配配置文件中自定义的一些内容!
要解决的问题
- 导入静态资源,。。
- 首页
- jsp,模板引擎Thymeleaf
- 装配拓展MVC
- CRUD
- 拦截器
- 国际化
- springsecurity shiro
总结:
- 在Springboot中我们可以使用以下方式处理静态资源
- webjars
- public, static,/**, resource
- 优先级 : resource>static(默认)>public
模板引擎
结论:只要需要使用thymeleaf,就必须导入对应的依赖!我们可以将html放在我们的templates目录下即可!
首页配置:注意点,所有页面的静态资源都需要使用thymeleaf接管;url@{}
页面国际化:
- 我们需要配置i18n
- 如果我们需要在项目中进行按钮自动化切换,我们需要自定义一个组件localeResolver
- 记得将自己写的组件配置到Spring容器中@Bean
- #{}
登录+拦截器
员工列表显示
-
提取公共页面
-
th:fragment="sidebar"
-
<div th:replace="~{commons/commons::topbar}"></div>
-
如果要传递参数,可以使用()传参,接收判断即可
-
-
列表循环展示
添加员工
- 按钮提交
- 跳转到添加页面
- 添加员工成功
- 返回首页
CRUD搞定
代码
package com.example.config;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
/**
* @author zcq17
*/
public class MyLocaleResolver implements LocaleResolver {
/**
* 解析请求
* @param request
* @return
*/
@Override
public Locale resolveLocale(HttpServletRequest request) {
String language = request.getParameter("l");
Locale locale = Locale.getDefault();
//如果不为空
if (!StringUtils.isEmpty(language)){
//zh_CN
String[] split = language.split("_");
//国家,地区
return new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
package com.example.config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.ManagedBean;
/**
* @author zcq17
*/
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
回顾
- springboot是什么
- 微服务
- Helloword
- 探究源码~自动装配
- 配置yml
- 多文档环境切换
- 静态资源映射
- thymeleaf
- SpringBoot如何拓展MVC javaconfig
- 如何修改SpringBoot的默认配置
- CRUD
整合Mybatis
整合包
Mybatis-spring-boot-starter
- 导入包
- 配置文件
- mybatis配置
- 编写sql
- 业务层调用dao层
- controller层调用service层
配置文件
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.example.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springbo0t-05-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbo0t-05-mybatis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
SpringSecurity(安全)
在web开发中安全第一位!过滤器拦截器
功能性需求:否
做网站:安全应该在什么时候考虑
- 漏洞,隐私泄露
- 架构一旦确定
shiro、springsecurity:很像,除了类不一样,名字不一样:
认证,授权(vip1,vip2,vip3)
- 功能权限
- 访问权限
- 菜单权限
- 拦截器,过滤器:大量的原生代码
aop横切~配置类
简介
SpringSecurity是针对Spring项目的安全框架,也是SpringBoot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入Spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理!
记住几个类:
- WebSecurityConfigureAdapter:自定义Security策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecurity模式
Spring Security的两个主要目标是“认证”和“授权”(访问控制)
认证:Authentication
授权:Authorization
这个概念是通用的,而不是只存在Security中存在
代码:
SecurityConfig
package com.zhou.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* @author zcq17
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 授权
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 首页所有人可以访问,功能页只能有对应权限得人可以访问
// AOP: 拦截器
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
// 没有权限默认调到登录页
http.formLogin();
// 开启注销功能
// http.rememberMe();
http.rememberMe().rememberMeParameter("rememberMe");
http.logout().logoutSuccessUrl("/");
}
/**
* 认证
* @param auth
* @throws Exception
* 密码编码:PasswordEncode
* 在SpringSecurity5.0+中新增了很多加密方式
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 这些数据应该从数据库中读取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("zhouxx").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
.and()
.withUser("zhoucc").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
package com.zhou.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author zcq17
*/
@Controller
public class RouterController {
@RequestMapping({"/","/index"})
public String index(){
return "index";
}
@RequestMapping("toLogin")
public String toLogin(){
return "views/login";
}
@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id")int id){
return "views/level1"+id;
}
@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id")int id){
return "views/level2"+id;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id")int id){
return "views/level3"+id;
}
}
Shiro
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kPV4DZZD-1605599028811)(C:\Users\zcq17\AppData\Roaming\Typora\typora-user-images\image-20200924204130939.png)]
- 导入依赖
- 配置文件
- HelloWorld
SpringSecurity都有
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
currentUser.isAuthenticated()
currentUser.getPrincipal()
currentUser.hasRole("schwartz")
currentUser.isPermitted("lightsaber:wield")
currentUser.logout();
SpringBoot中集成
代码
shiroConfig
package com.zhou.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.LinkedHashMap;
/**
* @author zcq17
*/
@Configuration
public class ShiroConfig {
/**
* ShiroFilterFactoryBean
*/
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
// 设置安全管理器
factoryBean.setSecurityManager(securityManager);
// 添加Shiro的内置过滤器
/**
* anon: 无需认证就可访问
* authc: 必须认证了才能访问
* user: 必须拥有记住我才能访问
* perms: 必须拥有对某个资源才能访问
* role: 拥有某个角色权限才能访问
*/
LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
factoryBean.setFilterChainDefinitionMap(filterMap);
factoryBean.setUnauthorizedUrl("/noauth");
// 设置登录的请求
factoryBean.setLoginUrl("/toLogin");
return factoryBean;
}
/**
* DefaultWebSecurityManager
*/
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 关联Realm
securityManager.setRealm(userRealm);
return securityManager;
}
/**
* 创建realm对象,需要自定义类
*/
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
// 整合ShiroDialect:用来整合我们的shiro和thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
Realm
package com.zhou.config;
import com.zhou.pojo.User;
import com.zhou.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author zcq17
*/
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
// 授权,
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 拿到当前登录的对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal();
// 设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
// 认证,
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthenticationInfo");
// 数据库中取用户名密码
UsernamePasswordToken userToken=(UsernamePasswordToken)token;
User user = userService.queryUserByName(userToken.getUsername());
if (!userToken.getUsername().equals(user.getUsername())){
return null;
}
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.setAttribute("loginUser",user);
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
任务
异步任务
定时任务
邮件任务
springboot集成Redis
分布式Dubbo+zookeeper
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-98ODvROb-1605599028812)(C:\Users\zcq17\AppData\Roaming\Typora\typora-user-images\image-20200929183340043.png)]
RPC 什么是RPC
RPC【Remote Procedure Call】是指远程过程调用,是一种进程间通信方式,它是一种技术思想,而不是规范。它允许程序调用另一个地址空间(通常是共享网络的另一台机器上)的过程或者函数,而不是程序员显示编码这个远程调用的细节。即程序员无论是调用本地的还是远程的函数,本质上编写的调用代码基本相同
步骤:
- 提供者提供服务
- 配置注册中心的地址,以及服务发现名,和要扫描的包~
- 在想要被注册的服务上面增加一个注解@Service(Dubbo的注解)
消费者如何消费
- 导入依赖
- 配置注册中心的地址,配置自己的服务名
- 从远程注入服务~@Reference
Vue.js 是什么
Vue.js(读音 /vjuː/, 类似于 view) 是一套构建用户界面的 渐进式框架。与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计。Vue 的核心库只关注视图层,并且非常容易学习,非常容易与其它库或已有项目整合。另一方面,Vue 完全有能力驱动采用单文件组件和 Vue 生态系统支持的库开发的复杂单页应用。
Vue.js 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。
如果你是有经验的前端开发者,想知道 Vue.js 与其它库/框架的区别,查看对比其它框架。
起步
官方指南假设你已有 HTML、CSS 和 JavaScript 中级前端知识。如果你是全新的前端开发者,将框架作为你的第一步可能不是最好的主意——掌握好基础知识再来!之前有其他框架的使用经验是有帮助的,但不是必需的。
尝试 Vue.js 最简单的方法是使用 JSFiddle Hello World 例子。你可以在浏览器新标签页中打开它,跟着我们学习一些基础示例。或者你也可以创建一个本地的 .html 文件,然后通过如下方式引入 Vue:
你可以查看安装指南来了解其他安装 Vue 的选项。请注意我们不推荐新手直接使用 vue-cli,尤其是对 Node.js 构建工具不够了解的同学。
声明式渲染
Vue.js 的核心是一个允许你采用简洁的模板语法来声明式的将数据渲染进 DOM 的系统:
var app = new Vue({
el: ‘#app’,
data: {
message: ‘Hello Vue!’
}
})
Hello Vue!
我们已经生成了我们的第一个 Vue 应用!看起来这跟单单渲染一个字符串模板非常类似,但是 Vue.js 在背后做了大量工作。现在数据和 DOM 已经被绑定在一起,所有的元素都是响应式的。我们如何知道?打开你的浏览器的控制台,并修改 app.message,你将看到上例相应地更新。
除了绑定插入的文本内容,我们还可以采用这样的方式绑定 DOM 元素属性:
var app2 = new Vue({
el: ‘#app-2’,
data: {
message: 'You loaded this page on ’ + new Date()
}
})
Hover your mouse over me for a few seconds to see my dynamically bound title!
这里我们遇到点新东西。你看到的 v-bind 属性被称为指令。指令带有前缀 v-,以表示它们是 Vue.js 提供的特殊属性。可能你已经猜到了,它们会在渲染过的 DOM 上应用特殊的响应式行为。这个指令的简单含义是说:将这个元素节点的 title 属性和 Vue 实例的 message 属性绑定到一起。
你再次打开浏览器的控制台输入 app2.message = ‘some new message’,你就会再一次看到这个绑定了title属性的HTML已经进行了更新。
条件与循环
控制切换一个元素的显示也相当简单:
Now you see me
var app3 = new Vue({
el: ‘#app-3’,
data: {
seen: true
}
})
Now you see me
继续在控制台设置 app3.seen = false,你会发现 “Now you see me” 消失了。
这个例子演示了我们不仅可以绑定 DOM 文本到数据,也可以绑定 DOM 结构到数据。而且,Vue.js 也提供一个强大的过渡效果系统,可以在 Vue 插入/删除元素时自动应用过渡效果。
也有一些其它指令,每个都有特殊的功能。例如, v-for 指令可以绑定数据到数组来渲染一个列表:
- {{ todo.text }}
var app4 = new Vue({
el: ‘#app-4’,
data: {
todos: [
{ text: ‘Learn JavaScript’ },
{ text: ‘Learn Vue’ },
{ text: ‘Build something awesome’ }
]
}
})
Learn JavaScript
Learn Vue
Build something awesome
在控制台里,输入 app4.todos.push({ text: ‘New item’ })。你会发现列表中多了一栏新内容。
处理用户输入
为了让用户和你的应用进行互动,我们可以用 v-on 指令绑定一个监听事件用于调用我们 Vue 实例中定义的方法:
{{ message }}
Reverse Messagevar app5 = new Vue({
el: ‘#app-5’,
data: {
message: ‘Hello Vue.js!’
},
methods: {
reverseMessage: function () {
this.message = this.message.split(’’).reverse().join(’’)
}
}
})
Hello Vue.js!
在 reverseMessage 方法中,我们在没有接触 DOM 的情况下更新了应用的状态 - 所有的 DOM 操作都由 Vue 来处理,你写的代码只需要关注基本逻辑。
Vue 也提供了 v-model 指令,它使得在表单输入和应用状态中做双向数据绑定变得非常轻巧。
{{ message }}
var app6 = new Vue({
el: ‘#app-6’,
data: {
message: ‘Hello Vue!’
}
})
Hello Vue!
用组件构建(应用)
组件系统是 Vue.js 另一个重要概念,因为它提供了一种抽象,让我们可以用独立可复用的小组件来构建大型应用。如果我们考虑到这点,几乎任意类型的应用的界面都可以抽象为一个组件树:
Component Tree
在 Vue 里,一个组件实质上是一个拥有预定义选项的一个 Vue 实例:
// Define a new component called todo-item
Vue.component(‘todo-item’, {
template: ‘
- This is a todo
- ’
})现在你可以另一个组件模板中写入它:
但是这样会为每个 todo 渲染同样的文本,这看起来并不是很酷。我们应该将数据从父作用域传到子组件。让我们来修改一下组件的定义,使得它能够接受一个 prop 字段:
Vue.component(‘todo-item’, {
// The todo-item component now accepts a
// “prop”, which is like a custom attribute.
// This prop is called todo.
props: [‘todo’],
template: ‘ - {{ todo.text }}
- ’
})现在,我们可以使用 v-bind 指令将 todo 传到每一个重复的组件中:
Vue.component(‘todo-item’, {
props: [‘todo’],
template: ‘ - {{ todo.text }}
- ’
})var app7 = new Vue({
el: ‘#app-7’,
data: {
groceryList: [
{ text: ‘Vegetables’ },
{ text: ‘Cheese’ },
{ text: ‘Whatever else humans are supposed to eat’ }
]
}
})Vegetables Cheese Whatever else humans are supposed to eat
这只是一个假设的例子,但是我们已经将应用分割成了两个更小的单元,子元素通过 props 接口实现了与父亲元素很好的解耦。我们现在可以在不影响到父应用的基础上,进一步为我们的 todo 组件改进更多复杂的模板和逻辑。
在一个大型应用中,为了使得开发过程可控,有必要将应用整体分割成一个个的组件。在后面的教程中我们将详述组件,不过这里有一个(假想)的例子,看看使用了组件的应用模板是什么样的:
与自定义元素的关系
你可能已经注意到 Vue.js 组件非常类似于自定义元素——它是 Web 组件规范的一部分。实际上 Vue.js 的组件语法参考了该规范。例如 Vue 组件实现了 Slot API 与 is 特性。但是,有几个关键的不同:
Web 组件规范仍然远未完成,并且没有浏览器实现。相比之下,Vue.js 组件不需要任何补丁,并且在所有支持的浏览器(IE9 及更高版本)之下表现一致。必要时,Vue.js 组件也可以放在原生自定义元素之内。 Vue.js 组件提供了原生自定义元素所不具备的一些重要功能,比如组件间的数据流,自定义事件系统,以及动态的、带特效的组件替换。