script标签引入vue方式开发如何写组件

时间:2023-03-10 04:20:19
script标签引入vue方式开发如何写组件

title: script标签引入vue方式开发如何写组件

date: 2020-05-08

sidebarDepth: 2

tags:

  • vue
  • 组件
  • script
  • 标签

    categories:
  • vue

转载自:https://www.cnblogs.com/xingxingclassroom/p/9140115.html

很多人知道.vue结构的单文件组件形式,不过这种单文件组件的结构如果要加入到现有的jquery项目中就比较麻烦了,那如果我们又想用vue来写模板,又不想引入vue-cli管理,那该怎么来写组件呢?

很多人知道.vue结构的单文件组件形式,不过这种单文件组件的结构如果要加入到现有的jquery项目中就比较麻烦了,那如果我们又想用vue来写模板,又不想引入vue-cli管理,那该怎么来写组件呢?别着急往下看!

1.首先在正常使用cdn引入jquery的项目中,也用script标签引入Vue.js文件。

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.js"></script>

2.为了方便测试我们在页面中写个按钮,这个按钮的作用就是要展示jquery和vue同时正确使用并不互相冲突。

<input id="btn" type="button" value="jquery操作">

3.下面进入正题,我们来定义我们的vue组件。

Vue.component("card",{
props:{//这里是组件可以接受的参数,也就是相当于面向原型写组件时的配置参数,用户可以传递不同参数,自己定义组件
cardTitle:{//卡片标题
type:String,
default:'这是一个卡片'
},
list:{//列表内容
type:Array,
default:[]
}
},
template:`
<div class="modal">
<div class="modal-header">
<h4>{{cardTitle}}</h4>
</div>
<div class="modal-content">
<div>
<slot name="modal-content">可以扩展的卡片内容</slot>
<ul>
<li v-for="(item,index) in list">{{item}}</li>
</ul>
</div>
</div>
<div class="modal-footer">
<slot name="modal-footer">
<input class="btn blue" type="button" value="ok" @click="okHandle" />
<input class="btn" type="button" value="cancel" @click="cancelHandle" />
</slot> </div>
</div>
`,
methods:{//这里定义的组件的方法,利用$emit()进行父子组件通信,子组件通过点击事件告诉父组件触发一个自定义事件,$emit()方法第二个参数也可以用来传递数据
okHandle(){
this.$emit("ok");
},
cancelHandle(){
this.$emit('cancel')
}
}
});

ps:代码中有slot的地方是分发内容的定制模板,slot为modal-content 定制提醒信息模板,slot为modal-footer 定制底部模板。你可以在父页面进行卡片样式的更改和功能的增减。定义好的这个组件在父页面中也要以script标签的形式引入进来,当然你也可以直接定义在父页面中,这个按照你自己的需求和逻辑来写。

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.js"></script>
<script src="./modal.js"></script>

4.父页面调用这个组件,最外层必须是vue的实例id为app的div元素包裹才行。

 <div id="app">
<div>
<card :list="list" @ok="okMethods" @cancel="cancelMethods"></card>
</div>
</div>

ps:使用jquery点击按钮触发一个dom操作的事件与vue实例对象中的组件之间并没有任何冲突,不过这里要注意的是,jquery的代码尽量不要写在vue实例的方法methods中,防止出现Bug,另外在htm的书写过程中,所有关于jquey的dom操作都最好也应该写在id为app的vue实例区域的外面,这样才能避免其他bug。

<script>
$('#btn').on('click',function(){
console.log('jquery操作');
})
new Vue({
el:'#app',
data:{
list:[1,2,3,4]
},
methods:{
okMethods:function (){
console.log("ok")
},
cancelMethods:function (){
console.log("cancel")
}
}
});
</script>

5.另一则案例

header.js

var headerTemplate = '<div> header HTML 代码</div>'
Vue.component('my-header', {
template: headerTemplate,
data: xxx,
methods: {}
// ...
})

通过 script标签引入 header.js, 然后在 header.html 内就可以使用了, 比如:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="vue.min.js"></script>
<script src="header.js"></script>
</head>
<body>
<div id="main">
<my-header></my-header>
</div> <script>
new Vue({
el: '#main'
})
</script>
</body>
</html>