Vue - 同时使用 ip、localhost访问项目

GitHub Demo 地址

在线预览

通过localhost运行起来只能在本机访问。有时调试需要在其他设备进行访问,这时需要通过IP地址进行访问。

效果:

解决办法:

步骤1:

步骤1的两种方法(1)、方法12)、方法2)使用一种就行

1)、方法1(推荐)

首先修改路径config/index.js中的host
host: 'localhost' 修改为 host: '0.0.0.0',

在这里插入图片描述
如果这时运行,结果如下
在这里插入图片描述

但是自动打开的网页是0.0.0.0开头的,如果想改成自动打开的网页以IP地址显示,需要进行如下操作:

路径build/webpack.dev.conf.js中的devServer添加 useLocalIp:true,
这样打开页面就会是ip:port的形式,同时你也可以通过localhost:port或127.0.0.1:port打开页面。

在这里插入图片描述

2)、方法2

也可以在package.json文件的 dev中 添加--host 0.0.0.0"

在这里插入图片描述

 "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js --host 0.0.0.0",

步骤2:

修改路径build/webpack.dev.conf.js中的messages

在这里插入图片描述

  // messages: [
  //   `Your application is running here: 
  //   http://${devWebpackConfig.devServer.host}:${port}`
  // ]
  messages: [
    `Your application is running here: `,
    `Local: http://localhost:${
      
      port}`,
    `Network: http://${
      
      require('ip').address()}:${
      
      port}`,
  ],

最终运行效果:
在这里插入图片描述
这时运行时自动打开的项目也是本地ip的地址

猜你喜欢

转载自blog.csdn.net/iotjin/article/details/129442185