由于各种原因,需要在原有的html页面中通过script标签引入的方式进行部分页面开发 但是由于开发过程中存在许多公共部分需要进行组件封装。所以遇到了一些问题。最后通过讲组件提取为单独js文件进行解决。
具体解决思路如下
首先将要封装的公用组件进行单独js文件提取
header.js

var headerTemplate = `<div v-show="aa" style="position:fixed;top:10%;left:30%"> <el-table
      :data="newlists"
      style="width: 100%">
      <el-table-column
        prop="date"
        label="日期"
        width="180">
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址">
      </el-table-column>
    </el-table><div @click="fun()">asdasd</div>
	<button @click="closefun">close</button></div> 
    `
Vue.component('my-header', {
    template: headerTemplate,
    props:{newlists:{type:Array}},
    data() {
    	return {
    		aa:true
    	}
          
      },
    	methods: {
    		closefun(){
    			console.log(this.$parent)
    			this.$emit('hello',"child2parent?")
    		}
    	}
    // ...
})

上面的部分为剥离的组件部分,通过接受父组件的值进行渲染,并回传父组件值
接下来则是使用组件
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
   	<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="header.js"></script>
</head>
<body>
    <div id="main">
    	<div v-show="haha">
        	<my-header  @hello="acceptValue" :newlists="list"></my-header>
        </div>
        <button @click="shanghucan">upload</button>
    </div>


    <script>
        new Vue({
            el: '#main',
            data(){
            	return {
            		haha:false,
			    	list: [{
			            date: '2016-05-02',
			            name: '王小虎',
			            address: '上海市普陀区金沙江路 1518 弄'
			          }, {
			            date: '2016-05-04',
			            name: '王小虎',
			            address: '上海市普陀区金沙江路 1517 弄'
			          }]
			    	}	
            	
            },
            methods:{
            	shanghucan(){
            		this.haha = true
            	},
            	acceptValue(data){
            		console.log(data)
            	}
            },
            created(){
            	console.log(this)
            }
        })
    </script>
      <style>
		.hahahha{
			width:500px;
			height:100px;
			background-color:red;
		}
    </style>
</body>
</html>

通过这样的方法我们 基本实现了公共组件的封装和使用,我们只需将组件部分引入index页面或者需要使用的页面则可实现在html页面通过script标签引入的方式下进行组件封装

Logo

前往低代码交流专区

更多推荐