页面正常渲染,控制台报错说data中的东西未定义!
wander lv.2
发布时间:2022-09-18 11:11:45 601相关标签: # webkit# ios# json# 信息# 工具
在infocenter.vue中发送修改的用户信息,在得到res后,向data中赋值改变,
会报错说data中的东西未定义!第一次碰到这种情况,也不知道怎么解决。
vue中159行开始
<template>
<div id="infocenter">
<!-- 头部标题栏 -->
<HeadTop title="个人信息中心">
<span slot="left">
<div @click="routerback">
<Icon type="md-arrow-round-back" size="20" /><span>返回</span>
</div>
</span>
<span slot="right"></span>
</HeadTop>
<!-- 内容 -->
<div>
<div class="upload">
<!-- 个人信息 -->
<div style="width:280px;margin:0 auto;text-align:center;">
<!-- 展示用户信息,可以修改 -->
<div v-if="showInfo">
<Form :model="info" label-position="right" :label-width="100">
<img :src="this.info.avatarurl" width="60" height="60"/>
<FormItem label="昵称:" style="text-align:left;">
{{this.info.username}}
</FormItem>
<FormItem label="简介:" style="text-align:left;">
{{this.info.disc}}
</FormItem>
</Form>
<Button type="warning" @click="changeInfo" ghost>修改</Button>
</div>
<!-- 修改用户信息表单 -->
<div v-if="showForm">
<Form :model="info" label-position="left" :label-width="100">
<div>
<img @click.stop="uploadHeadImg" :src="this.info.avatarurl" width="60" height="60"/>
<input type="file" accept="image/*" @change="handleFile" id="hiddenInput" />
</div>
<FormItem label="昵称">
<Input v-model="info.username" />
</FormItem>
<FormItem label="简介">
<Input type="textarea" v-model="info.disc" :autosize="{minRows: 2,maxRows: 5}" />
</FormItem>
</Form>
<Button type="success" @click="sureInfo" ghost>确定</Button>
<Button type="info" @click="cancelInfo" ghost>取消</Button>
</div>
{{this.info}}
{{this.oldinfo}}
</div>
<!-- 上传图片 -->
<div v-if="true">
<!--图片上传-->
<div class="weui-gallery" id="gallery">
<span class="weui-gallery__img" id="galleryImg"></span>
<div class="weui-gallery__opr">
<a href="javascript:" class="weui-gallery__del">
<i class="weui-icon-delete weui-icon_gallery-delete"></i>
</a>
</div>
</div>
<div class="weui-cells weui-cells_form">
<div class="weui-cell">
<div class="weui-cell__bd">
<textarea class="weui-textarea" v-model="content" placeholder="你想说啥" rows="3"></textarea>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__bd">
<div class="weui-uploader">
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="uploaderFiles">
<li ref="files" class="weui-uploader__file" v-for="(image,index) in images" :key="index"
:style="'backgroundImage:url(' + image +' )'"><span @click="deleteimg(index)" class="x">×</span></li>
</ul>
<div v-show="images.length < maxCount" class="weui-uploader__input-box">
<input @change="change" id="uploaderInput" class="weui-uploader__input " type="file"
multiple accept="image/*">
</div>
</div>
</div>
</div>
</div>
</div>
<a class="weui-btn weui-btn_primary btn-put" style="margin: 20px " @click.prevent.once="put">发送</a>
</div>
</div>
</div>
</div>
</template>
<script>
import store from '../../vuex/store'
import HeadTop from '../components/HeadTop/HeadTop'
import axios from 'axios'
export default {
name:"Infocenter",
data(){
return {
//用户框,修改框 展示与否
showInfo:true,
showForm:false,
//用户信息(来接受路由传递过来的query),并且在界面上动态改变,如果用户确定则向后台提交
info:{},
//缓存用户信息,防止取消修改信息后原信息丢失
oldinfo:{},
//待上传的图片文件
pic_file:{},
//上传头像相关
content: '',//分享动态的文字内容
maxSize: 10240000 / 2,//图片的最大大小
maxCount: 8,//最大数量
filesArr: [],//保存要上传图片的数组
images: []//转成base64后的图片的数组
}
},
//引入vuex
store,
//引入子组件
components: {
HeadTop,
},
//方法
methods:{
//后退:返回上一个页面
routerback(){
this.$router.back(-1);
},
changeInfo(){
// 用户信息框消失,修改信息框展示
this.showInfo = false;
this.showForm = true;
},
sureInfo(){//确定修改用户信息,并提交给后台
// 用户信息框展示,修改信息框消息
this.showInfo = true;
this.showForm = false;
//添加接口所需的数据file--头像,username--用户名,disc--简介,_id--唯一标识
var formData=new FormData();// 创建form对象:接口所需的所有数据formData
formData.append('file',this.pic_file);
formData.append('username', this.info.username);
formData.append('disc', this.info.disc);
formData.append('_id', this.info._id);
console.log('打印formData')
console.log(formData)
axios.post('http://localhost:4444/shangchuan', formData, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function (res) {
alert('修改个人信息成功!!!');
console.log(res)
console.log(this.oldinfo)
console.log(this.info)
this.info.avatarurl = res.data.avatarurl;
console.log(res.data);
this.$router.push({path: '/me'});
})
.catch(err=>{
alert('修改个人信息失败!');
console.log(err);
})
},
cancelInfo(){ //取消 修改用户信息
// 用户信息框展示,修改信息框消息
this.showInfo = true;
this.showForm = false;
//缓存用户信息,防止取消修改信息后原信息丢失
this.info = Object.assign({}, this.oldinfo);
},
//头像上传
// 打开图片上传
uploadHeadImg: function () {
this.$el.querySelector('#hiddenInput').click();
},
//点击图片触发 将头像显示(不涉及上传图片)
handleFile: function (e) {
let $target = e.target || e.srcElement;//找到input节点
let file = $target.files[0];//找到上传的图片
this.pic_file = $target.files[0];//存入data中
//初始化this.formData
this.formData = new FormData();
// 单纯将头像显示
var reader = new FileReader();//将文件内容读入内存,访问本地文件
reader.onload = (data) => {//当读取操作成功完成时调用
let res = data.target || data.srcElement;//捕获当前事件作用的对象
this.info.avatarurl = res.result;//图片被转换成了二进制流(字符串类型),存储在info的avatarurl中
};
reader.readAsDataURL(file);//将图片内嵌在网页之中--Base64
},
// 上传头像相关的所有方法--开始
//删除图片
deleteimg(index) {
this.filesArr.splice(index, 1);
this.images.splice(index, 1);
},
//改变图片
change(e) {
let files = e.target.files;
// 如果没有选中文件,直接返回
if (files.length === 0) {
return;
}
if (this.images.length + files.length > this.maxCount) {
Toast('最多只能上传' + this.maxCount + '张图片!');
return;
}
let reader;
let file;
let images = this.images;
for (let i = 0; i < files.length; i++) {
file = files[i];
this.filesArr.push(file);
reader = new FileReader();
if (file.size > self.maxSize) {
Toast('图片太大,不允许上传!');
continue;
}
reader.onload = (e) => {
let img = new Image();
img.onload = function () {
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
let w = img.width;
let h = img.height;
// 设置 canvas 的宽度和高度
canvas.width = w;
canvas.height = h;
ctx.drawImage(img, 0, 0, w, h);
let base64 = canvas.toDataURL('image/png');
images.push(base64);
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
},
//发送方法
put() {
let self = this;
let content = this.content;
let param = new FormData();
param.append('content', content);
param.append('username', 'wofsfsdf');
this.filesArr.forEach((file) => {
param.append('file2', file);
});
axios.post('http://localhost:4444/uploadFile', param, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function (result) {
console.log(result.data);
this.$router.push({path: '/world'});
Toast(result.data.msg)
})
},// 上传头像相关的所有方法--结束
},//methods-end
//beforeCreate 将路由中的 用户信息 赋值到 data(){} 中
beforeCreate(){
//防止token已经过期
var localtoken = localStorage.getItem("token");
var localusername = localStorage.getItem("user_name");
var localparams = {
token:localtoken,
user_name:localusername
};
this.$axios({
url:"http://localhost:4444/users/islogin",
method:"get",
params:localparams
})
.then(res=>{
console.log('这里是vue初始化生命周期:');
if(res.data.status == 200){
this.info = res.data.info;
//对象赋值,分配一块新的内存空间
this.oldinfo = Object.assign({}, this.info);
console.log(res.data.info);
}
})
.catch(err=>{
console.log(err)
})
},//beforreCreate-end
}
</script>
<style scoped>
#hiddenInput{
display: none;
}
</style>
index.js
var express = require('express');
var router = express.Router();
var path = require("path");
var User = require("../models/User");
var Info = require("../models/Info");
//图片上传模块
var multer = require('multer');
let OSS = require('ali-oss');
//阿里云oss配置自己去官网瞧
let client = new OSS({
region: 'oss-cn-shanghai',
accessKeyId: '****',
accessKeySecret: '******'
});
client.useBucket('******');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
async function put(fileName, filePath, cb) {
try {
let result = await client.put(fileName, filePath);
fs.unlinkSync("public/images/uploads/" + result.name);
cb(result)
} catch (err) {
console.log(err);
}
}
let filePath;
let fileName;
let Storage = multer.diskStorage({
destination: function (req, file, cb) {//计算图片存放地址
cb(null, './public/images/uploads');
},
filename: function (req, file, cb) {//图片文件名
fileName = Date.now() + '_' + parseInt(Math.random() * 1000000) + '.png';
filePath = '/public/images/uploads/' + fileName;
cb(null, fileName)
}
});
let upload = multer({ storage: Storage }).any();//file2表示图片上传文件的key
//自己写的用户信息接收
router.post('/shangchuan', function (req, res, next) {
upload(req, res, function (err) {
let content = req.body.content || "";
let username = req.body.username;
let imgs = []; //要保存到数据库的图片地址数组
if (err) {
return res.end(err);
}
console.log('进入图片解析--------req.body')
console.log(req.body)
console.log('打印 req.files------')
console.log(req.files)
// console.log("打印 req.files[0].path------");
// console.log(req.files[0].path);
// console.log(content)
// console.log(content)
// console.log(username)
req.files.forEach((item, index) => {
var filePath = `http://localhost:4444/public/images/uploads/${item.filename}`;
console.log('数据库中的路径filePath------------')
console.log(filePath)
});
res.json({
avatarurl: filePath,
mag: "修改个人信息成功"
});
});
});
//网络查的 接收用户信息
router.post('/uploadFile', function (req, res, next) {
upload(req, res, function (err) {
let content = req.body.content || '';
let username = req.body.username;
let imgs = [];//要保存到数据库的图片地址数组
if (err) {
return res.end(err);
}
if (req.files.length === 0) {
new Pyq({
writer: username,
content: content
}).save().then((result) => {
res.json({
result: result,
code: '0',
msg: '上传成功'
});
})
}
/*client.delete('public/img/1.png', function (err) {
console.log(err)
});*/
let i = 0;
req.files.forEach((item, index) => {
let filePath = `./public/images/uploads/${item.filename}`;
put(item.filename, filePath, (result) => {
imgs.push(result.url);
i++;
if (i === req.files.length) {
//forEach循环是同步的,但上传图片是异步的,所以用一个i去标记图片是否全部上传成功
//这时才把数据保存到数据库
new Pyq({
content: content,
writer: username,
pimg: imgs
}).save().then(() => {
res.json({
code: '0',
msg: '发布成功'
});
})
}
})
})
})
});
module.exports = router;
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
//加载数据库模块
var mongoose = require("mongoose");
// 引入jwt token工具
const JwtUtil = require('./public/utils/jwt');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
//解决跨域
app.all('*', function (req, res, next) {
//将外源设为指定的域,比如:http://localhost:8080
res.header("Access-Control-Allow-Origin", "*");
//将Access-Control-Allow-Credentials设为true 允许携带cookie
res.header('Access-Control-Allow-Credentials', true);
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
//配置options的请求返回,解决axios的post自定义头部字段问题
// if (res.getMethod().equals("OPTIONS")) {
// HttpUtil.setResponse(response, HttpStatus.OK.value(), null);
// return;
// }
//返回数据格式为json字符串
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/public', express.static('public'));//将文件设置成静态
// app.use(express.static(path.join(__dirname, 'public')));
/* 请求拦截器
*/
// app.use(function (req, res, next) {
// var url = req.url;
// // 正则表达式匹配 匹配api '?' 前的路径,去除query参数
// url = url.match(/(\S*)\?/)[1];
// // console.log('匹配正则后');
// // console.log(url);
// // 把登陆和注册请求去掉了,其他的多有请求都需要进行token校验
// if (url != "/users/login" && url != "/users/register") {
// console.log("进入app.js拦截器,打印result");
// /*没有弄明白怎么在headers中设置token
// let token = req.headers.token;
// */
// let token = req.query.token;
// let jwt = new JwtUtil(token);
// let result = jwt.verifyToken();
// // 如果考验通过就next,否则就返回登陆信息不正确(与jwt.js返回有关)
// if (result == 'err') {
// console.log('token已过期,被拦截器拦截');
// console.log(result);
// res.send({ status: 403, msg: "尚未登录(登录已过期),请重新登录!" });
// } else {
// console.log('token没过期,进入对应的路由')
// next();
// }
// } else {
// //放过 登录 和 注册 请求
// next();
// }
// });
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
//连接数据库
mongoose.connect('mongodb://localhost:27222/blog', function (err) {
if (err) {
console.log(err);
console.log('数据库连接失败!');
} else {
console.log("数据库连接成功!");
}
});
module.exports = app;
文章来源: https://blog.51cto.com/u_14187652/5672599
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报