vue基础进阶(二)

VUE

一. vue-cli构建项目与打包部署

​ 使用vue-cli能够快速的帮助我们构建项目,它就如同一个脚手架,提供了可选的模板。在使用vue-cli之前需要先安装nodejs。

1.1 使用npm构建项目
npm install -g @vue/cli             #安装vue-cli,该步骤需要等一段时间
vue -V                              #查看vue-cli的版本
vue create my-app                   #创建名为my-app的项目
1.2 项目的结构介绍
  • public: 存放静态文件。
  • src: 源码文件,开发就在此目录下。
  • .gitignore: git的配置文件。
  • babel.config.js: babel的配置文件,在创建项目的时候才用的脚手架为bable。
  • package-lock.json:定义了依赖库的下载位置,保证了在项目迁移部署环境的一致性。
  • package.json: 定义了该项目依赖的类库。
1.3 项目的打包部署

执行命令:

npm run build

将生成的dist目录下的文件放入到tomcat或者nginx下,启动服务器,即可访问。

二. 组件化开发

​ 组件化开发是在ES6中提出的,可以提高页面的复用率,提高开发效率,便于团队协作,是一套模板化的代码,要有<template><script><style>三个标签,分别用来定义布局、脚本和样式。而且<template>下必须有一个根节点。

2.1 编写App.vue和HelloWorld.vue

HelloWorld.vue

<template> 
	<div>  <!-- template的根节点,是必须的 -->
		<h1 class="title">{{msg}}</h1>
	</div>
</template>
<script>
	export default {   <!-- 向外保留成员,表示向外暴露该组件 -->
		data() {
			return {
				msg: 'Hello World'
			}
		} 
	}
</script>
<style>
	.title{
		color: red;
	}
</style>

App.vue

<template>
    <div>
        <p>{{article}}</p>
        <Helloworld></Helloworld> <!-- 在Helloworld.vue中的组件 -->
    </div>
</template>
<script>
/**
 * 引入HelloWorld.vue组件,使用Helloworld变量来接收,接收变量的组件
 * 可以叫任何名字,但是推荐使用和导入组件保持一致。
 */
import Helloworld from './components/HelloWorld.vue'

export default {
	/**
     *  需要在当前组件中来定义引入的组件,接收的形式可以有二种:
     * 
     *  components: {HelloWorld} 最原始的写法为{Helloworld:Helloworld},第一个Helloworld
     *     在当前组件中使用的名字,可以随意更改,第二个Helloworld是上面import引入的时候用来接收的变
     *     量名。如果只写一个表示当前组件中使用的名字和变量名一致。 
     */
    components: {Helloworld},
    data(){   //组件化编程必须使用定义data方法
        return {
            article: '路透社20日援引伊朗法尔斯通讯社消息称'
        };
    }
}
</script>
<style>
</style>
2.2 定义入口JS文件
import Vue from 'vue'        //引入vue
import App from './App.vue'  //引入自己定义的App.vue,使用变量App来接收

new Vue({
    render: h => h(App),  //将App组件渲染到index.html中。
}).$mount("#app")

render是Vue中的一个方法,方法的定义形式如下:

// render最原始的,而传入的参数createElement又是一个函数,用来生成dom结构
render: function(createElement){
    
}
// 按照ES6的箭头函数的写法,进行第一次演变
render: createElement => createElement(模板)
// 将上面的createElement变为h,那么就得到最终的形式
render: h => h(App)

$mount("#id")该方法的作用是先实例化Vue对象,接着在挂载到指定Id的节点上,和在**new Vue**的时候使用el指定要渲染的节点的形式是一样的,只是换了种形式而已。

三. 案例演示

案例一:利用组件化编程实现如下图示案例:

在这里插入图片描述

案例二:利用组件化编程实现如下图案例(并实现数据的存储):

在这里插入图片描述

​ 此案例非常经典,当你能够独立的完成如上两个案例,表示你已经比较深入的理解VUE了 _

四. 组件通信

4.1 props

父组件 App.vue

<template>
	<div>
		<h1>Hello World</h1>
		<!-- 前面一个msg标识子组件用于接收的变量名, 引号中的msg是当前组件的值 
			 第一个add是子组件用于接收的变量名,第二个add是当前组件的方法名
		-->
		<child :msg="msg" :add="add"/> 
	</div>
</template>
<script>
import child from './Child.vue'
export default {
	data() {
        return {
            msg: '这个信息来源于父组件'
        };
	},
	method: {
        add() {
            alert('add method');
        }
	}
}
</script>
<style></style>

子组件 Child.vue

<template>
	<div>
		<p>{{msg}}</p>
		<button @click="addItem" />
	</div>
</template>
<script>
export default {
	// 使用props接收父组件传递过来的值
	props: {  
        msg: String,
        add: Function
	}
	method: {
        addItem() {
            this.add(); //调用父类的add方法
        }
	}
}
</script>
<style></style>
4.2 事件绑定、监听与取值
4.2.1 子组件操作父组件

父组件 App.vue

<template>
  <div>
     <input type="text" v-model="value">
     <hr>
     <Child @dosomething="changeValue"/>
  </div>
</template>

<script>
import Child from './components/Child.vue'

export default {
  components: {
    Child
  },
  data() {
    return {
      value: ''
    }
  },
  methods: {
    changeValue(value) {
      this.value = value;
    }
  }
}
</script>
<style>
</style>

子组件 Child.vue

<template>
    <div>
        <button @click="dosomething">子组件按钮</button>
    </div>
</template>

<script>
export default {
    methods: {
        dosomething() {
        	// 调用父组件绑定的事件 dosomething,然后调用changeValue方法,并传值
            this.$emit('dosomething', '张某人');
        }
    }
}
</script>
<style>
</style>
4.2.2 父组件监听子组件

父组件 App.vue

<template>
  <div>
     <input type="text" v-model="value">
     <hr>
     <Child ref="child"/>
  </div>
</template>

<script>
import Child from './components/Child.vue'

export default {
  components: {
    Child
  },
  mounted() {
    // 将当前组件中的changeValue方法,绑定到名为changeValue中监听事件中,
    // 子组件通过 this.$emit('changeValue', '张某人') 变会调用父组件的changeValue方法
    this.$refs.child.$on('changeValue', this.changeValue);
  },

  data() {
    return {
      value: ''
    }
  },
  methods: {
    changeValue(value) {
      this.value = value;
    }
  }
}
</script>
<style>
</style>

子组件 Child.vue

<template>
    <div>
        <button @click="dosomething">子组件按钮</button>
    </div>
</template>

<script>
export default {
    data() {
        return {
            value: '张某人'
        }
    },
    methods: {
        dosomething() {
            this.$emit('changeValue', '张某人');
        }
    }
}
</script>
<style>
</style>
4.2.3 父组件取子组件中的值

父组件 App.vue

<template>
  <div>
     <input type="text" v-model="value">&nbsp;&nbsp;
     <button @click="changeValue">取子组件的值</button>
     <hr>
     <Child ref="child"/>
  </div>
</template>

<script>
import Child from './components/Child.vue'

export default {
  components: {
    Child
  },
  data() {
    return {
      value: ''
    }
  },
  methods: {
    changeValue() {
      this.value = this.$refs.child.value;
    }
  }
}
</script>
<style>
</style>

子组件 Child.vue

<template>
    <div>
        <p>我是子组件,我中间定义了一个value='张某人'的数据</p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            value: '张某人'
        }
    }
}
</script>
<style>
</style>
4.3 订阅与发布

​ 订阅与发布可以应用到各种场景之下,不仅仅是父子组件之间,也可以应用于兄弟组件之间。

安装pubsub-js这个类库:

npm install pubsub-js --save

父组件 App.vue

<template>
  <div>
     <input type="text" v-model="value"/>
     <hr>
     <Child ref="child"/>
  </div>
</template>

<script>
import Child from './components/Child.vue'
import PubSub from 'pubsub-js'

export default {
  components: {
    Child
  },
  data() {
    return {
      value: ''
    }
  },
  mounted() {
    PubSub.subscribe('channel1', (msg, value) => {
      this.changeValue(value);
    });
  },
  methods: {
    changeValue(value) {
        this.value = value;
    }
  }
}
</script>
<style>
</style>

子组件 Child.vue

<template>
    <div>
        <button @click="pub">子组件发布消息</button>
    </div>
</template>

<script>
import PubSub from 'pubsub-js'

export default {
    methods: {
        pub() {
            PubSub.publish('channel1', '张某人');
        }
    }
}
</script>
<style>
</style>
4.4 插槽(slot)

​ 插槽的作用说白了就是一个占位的作用。

父组件 App.vue

<template>
  <div>
     <input type="text" v-model="value"/>
     <hr>
     <Child>
     	<!-- slot的值一定要与slot标签的name属性保持一致 -->
       <button @click="changeValue" slot="my-btn">改变数据</button>
     </Child>
  </div>
</template>

<script>
import Child from './components/Child.vue'

export default {
  components: {
    Child
  },
  data() {
    return {
      value: ''
    }
  },
  methods: {
    changeValue() {
        this.value = '张某人';
    }
  }
}
</script>
<style>
</style>

子组件 Child.vue

<template>
    <div>
        <slot name="my-btn"></slot>
    </div>
</template>

<script>
export default {
}
</script>
<style>
</style>

五. 网络请求

​ vue2.X版本中,官方推荐的网络请求的工具是axios。

npm install axios vue-axios --save
5.1 配置全局请求地址

​ 新建Base.vue文件,文件内容如下:

<script>
const BASE_URL = "http://localhost:8081"
export default {
BASE_URL
}
</script>
5.2 main.js配置
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import Base from './Base.vue'

Vue.use(VueAxios, axios);  //顺序有关系
axios.defaults.baseURL = Base.BASE_URL  //配置基本地址

new Vue({
  render: h => h(App),
}).$mount('#app')
5.3 发送GET请求
this.axios.get('/user'
    /**  可以通过如下方式,添加请求头信息
    ,{
         headers: {
             'token': 'hyfetrrabcpo'
         }
      }
    */
    )
    .then((resp) => {  // 请求成功
      this.users = resp.data;  
    }, (error) => { //请求失败
       window.console.log(error);  //不能直接用console
    })
5.4 发送POST请求
this.axios.post('/user', {name:'zhangsan', id: 10})  //后台必须要用json接收
	.then((resp) => {
			this.users = resp.data;
	}, (error) => {
			window.console.log(error);  //不能直接用console
	})
5.5 发送DELELE请求
this.axios.delete('/user/56')
	.then((resp) => {
			this.users = resp.data;
	}, (error) => {
			window.console.log(error);  //不能直接用console
	})

附录:

1.spring boot跨域支持

​ A. 在controller或者对应的方法上加上如下代码

@CrossOrigin(origins = {"http://localhost:8080"})

​ B. 基于过滤器的跨域支持

@Configuration
public class MyConfiguration {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://domain1.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值